Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is it okay to call free with null pointer?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading