Here’s something that I don’t quite understand. Maybe too much pointer acrobatics.
I have a helper function that replaces the common swap operation that you have in many sorting algorithms. This is the pattern (the array contains pointers to the actual data):
void *temp = array[i];
array[i] = array[j];
array[j] = temp;
Now, if I write my swap function so that it takes just two pointers to pointers, i.e. pointers to single slots in the array:
void swap(void **fst, void **snd)
{
void *temp = *fst;
*fst = *snd;
*snd = temp;
}
…, then my code keeps working, everything is sorted just fine, but Valgrind complains about invalid writes.
However, if I do the same thing by passing the array and two indices:
void swap(void **array, unsigned int i, unsigned int j)
{
void *temp = array[i];
array[i] = array[j];
array[j] = temp;
}
…, then everything works and Valgrind is happy.
As far as I can tell, both versions should do the same thing, except that in the first I grab the array slots beforehand.
Why does Valgrind complain although the result is the same and apparently correct?