Free null pointer anyway or check first?

Suppose I came across an instance in a program where I would either free the NULL pointer, or first check if it was NULL and skip the call to the free() function.

Would it be more efficient to just free the NULL pointer? I searched a bit and, apparently, for C89 post implementations, it is harmless to free the NULL pointer, so the solution comes down to efficiency.

My presumption is that when you call free() can potentially have quite a bit of overhead. Thus, perhaps a simple logical check before calling the free() function is absolutely necessary.


tl; dr version,

What happens internally when a call to free() is called, which can make it more or less efficient, to first check if the pointer is NULL before being released?

+6
source share
3 answers

The C standard ensures that calling free(NULL) is harmless and has no effect. So, if you do not think that calling free() with a NULL pointer indicates that you have a logical error elsewhere in your program, there is no reason to double-check this.

+8
source

Do not check the nullness value yourself. free should already do this anyway and does not guarantee anything when called with a null pointer. Just like that.

+7
source

The Open Group specification for free() states that:

If ptr is a null pointer, there will be no action.

This means that the implementation of free() will probably start with something that:

 if (ptr == NULL) return; 

which will have very little overhead. There are no guarantees, but not much work that the function could have done before it checks this check, so the check is not needed on its own.

+4
source

Source: https://habr.com/ru/post/953737/


All Articles