Suppose I came across an instance in a program where I would either free a NULL pointer, or first check whether it was NULL and skip the free()
function call.
Would it be more efficient to simply free a NULL pointer? I searched around a bit and apparently, for implementations post C89, it is harmless to free a NULL pointer - so the decision comes down to efficiency.
My presumption is that there may potentially entail quite a bit of overhead when calling free()
. As such, perhaps the simple logical check before calling the free()
function is quite necessary.
tl;dr version,
What is happening internally when a call to free()
is made that may make it more or less efficient to first check whether or pointer is NULL before freeing?
It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.
[16.8] Do I need to check for NULL before delete p? No! The C++ language guarantees that delete p will do nothing if p is equal to NULL.
See: man free The free() function deallocates the memory allocation pointed to by ptr. If ptr is a NULL pointer, no operation is performed. When you set the pointer to NULL after free() you can call free() on it again and no operation will be performed.
free() Parameters The pointer may be null or may not point to a block of memory allocated by calloc, malloc or realloc functions. If ptr is null, the free() function does nothing. If ptr does not point to a memory block allocated by calloc, malloc or realloc functions, it causes undefined behavior.
The C standard guarantees that calling free(NULL)
is harmless and has no effect. So, unless you believe that calling free()
on a NULL pointer indicates that you've got a logic error elsewhere in your program, there's no reason to double-check that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With