7

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?

7
  • What? The tldr has nothing to do with your question!
    – Kerrek SB
    Sep 12, 2013 at 22:56
  • Made it a bit more specific, but it was the overhead associated with calling free() that I was concerned with.
    – sherrellbc
    Sep 12, 2013 at 23:02
  • free(NULL) is guaranteed to be a no-op since c89. BTW: don't be too obsessed by performance. The only difference is the NULL-check being done inside or outside the free() function. Sep 12, 2013 at 23:05
  • 1
    @wildplasser: No, the difference is between the check being done inside or inside and outside.
    – Kerrek SB
    Sep 12, 2013 at 23:07
  • 2
    Possible duplicate of Does free(ptr) where ptr is NULL corrupt memory? Jan 5, 2016 at 9:50

3 Answers 3

11

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.

8

Don't check for nullness yourself. free already has to do that anyway and is guaranteed to do nothing when called with a null pointer. Simple as that.

1
  • I see - so this is how the NULL free is harmless.
    – sherrellbc
    Sep 12, 2013 at 22:58
4

The Open Group specification for free() states that:

If ptr is a null pointer, no action shall occur.

This implies that the implementation of free() will probably begin with something to the effect of:

if (ptr == NULL)
    return;

which will have very little overhead. No guarantees, but there isn't much work the function could do before it makes that check, so checking on your own is unnecessary.

1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.