Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free a null pointer anyway or check first?

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?

like image 840
sherrellbc Avatar asked Sep 12 '13 22:09

sherrellbc


People also ask

Should you free a null pointer?

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.

Do I need to check for null before delete p?

[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.

What will occur if we call free function on null pointer?

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.

What happens when the call free ptr ); is executed and ptr is null?

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.


1 Answers

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.

like image 61
This isn't my real name Avatar answered Nov 09 '22 06:11

This isn't my real name