Friday, October 5, 2007

Free'ing memory in C (free_ptr)

What?
The free_ptr(void** pptr) function causes the allocated memory referenced by *pptr to be made available for future allocations and sets *pptr to NULL.



void free_ptr(void** pptr)
{
if ((void **) 0 != pptr && (void *) 0 != *pptr)
{
free(*pptr);
*pptr = (void *) 0;
}
}



Why?
In general, to avoid bad code that would normally get written after the call to free(ptr). This bad code may not be written until weeks or months later and it may not be written by you, but it will get written by someone. :)

  1. Double Free - After you free the memory referenced by ptr bad code comes along and does it again. Results are unpredictable and system dependent.


  2. Dirty Read - If ptr is not NULL after it is free'd bad code could be added that tries to read the contents of the memory at ptr. Worst case is that 99% of the time the memory will contain the same values as it did before the call to free(ptr), but 1% of the time it will not and you will end up with a bug that is hard to reproduce. If you try to read from NULL, on the other hand, you will likely get a segment violation, garbage data, or some other signal from the operating system that you have done something wrong.


  3. Dirty Write - Bad code gets added after the call to free(ptr) that tries to write to ptr. Sometimes nothing happens because no one else is using the memory and sometimes everything blows up.

No comments: