It's clear from the C standards that NULL
is an acceptable input to free()
, with the result being no operation performed. However, this seems to violate the idea that free()
must only be called on memory that was explicitly allocated using malloc()
, calloc()
, or realloc()
.
What's the reasoning behind this exception? The only reason I can figure is so that callers do not have to explicitly check for NULL
before calling free()
.
CodePudding user response:
The malloc
function (as well as calloc
and realloc
) may return a NULL pointer if the requested size is 0. Therefore, it makes sense that NULL pointer can also be passed to free
since it was returned from a successful call to malloc
:
Section 7.22.3p1 of the C standard specifies this behavior:
If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.