Rick

Authored Comments

Re: 4. Freeing memory twice

To expand on this tip, the pointer should be NULL'ed immediately after calling free() to release the memory back to the heap.

By not NULL'ing the pointer results in two potential problems:

1) Calling free() twice on the same address, resulting in the corruption of the heap.

2) De-referencing the pointer to the freed memory, that might be in use by some other part of the program, possibly corrupting the data or retrieving incorrect data.

The solution is simple;

Either ALWAYS:

//...
free(array);
array = NULL;
//...

Many programmers forget to do this, or better still:

void *free2(void *ptr) // or some other name
{
free(ptr);
return NULL;
}

And consistently using the new function as:

array = free2(array);

This cures both issues above.

De-referencing a NULL pointer should result in a segmentation error, indicating an issue with the pointer, and calling free() on a NULL pointer has no effect.

In the section, "Loop until I guess the random number", I would code the loop with a while loop instead of a do-while loop. It is generally accepted to avoid the do-while loops if at all possible, and I agree. C++ as well!