Wednesday, December 16, 2009

Checking for NULL pointer before deleting or calling free()

Today after reading two posts (references given at the end) from Stack Overflow I have got a better understanding of how dynamically allocated memory should be freed and why in that way.

Earlier I knew only that pointer should be checked against NULL before freeing memory, otherwise catastrophic disaster may occur because it may happen that an already freed memory is being freed again. So I always put it like:

if (pointer == NULL) {
    free(pointer); // or "delete pointer;" in C++
}

Later while working with files in C, I came to realize that freeing memory in this fashion does not make the pointer NULL. So dangling pointer surfaces in this context. I added another line:

pointer = NULL;

However, freeing a NULL pointer is not a problem at all now because according to ANSI standard, free() function does nothing when the passed pointer is NULL.

For the sake of being cautious and avert non-standard compilers from causing havoc to your program, you may check for NULL pointer. Otherwise, it all boils down to only the following 2 lines:

delete pointer;
pointer = NULL;


References:

(1) checking for NULL before calling free
(2) Is there any reason to check for a NULL pointer before deleting?

No comments:

Post a Comment