Muddled brain because of too many swaps?

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?

Ooof! Grabbed some coffee and I suddenly understood what was going on. Stupid me.

I was calling the first version with swap(array[i], array[j]), so I actually dereferenced the pointers before passing them in. C swapped the data on the heap (random integers) instead of the pointers in the array as best it could, but pointers are larger than integers on my system so Valgrind complained.

Lesson learned. Drink more coffee.

I was about to say that, or you didn’t initalize the original array elements before calling the function. This is why Valgrind is so useful. C just goes ahead and lets you blow your face off.

A free service run by Zed A. Shaw for learncodethehardway.org.