Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 457 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Free a null pointer anyway or check first?

#1
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?
Reply

#2
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.
Reply

#3
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.
Reply

#4
[The Open Group specification for `free()`](

[To see links please register here]

) 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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through