checking for NULL before calling free

Viewed 14943

Many C code freeing pointers calls:

if (p)
  free(p);

But why? I thought C standard say the free function doesn't do anything given a NULL pointer. So why another explicit check?

8 Answers

The construct:

free(NULL);

has always been OK in C, back to the original UNIX compiler written by Dennis Ritchie. Pre-standardisation, some poor compilers might not have fielded it correctly, but these days any compiler that does not cannot legitimately call itself a compiler for the C language. Using it typically leads to clearer, more maintainable code.

As I understand, the no-op on NULL was not always there.

In the bad old days of C (back around 1986, on a pre-ANSI standard cc compiler) free(NULL) would dump core. So most devs tested for NULL/0 before calling free.

The world has come a long way, and it appears that we don't need to do the test anymore. But old habits die hard;)

http://discuss.joelonsoftware.com/default.asp?design.4.194233.15

I tend to write "if (p) free(p)" a lot, even if I know it's not needed.

I partially blame myself because I learned C the old days when free(NULL) would segfault and I still feel uncomfortable not doing it.

But I also blame the C standard for not being consistent. Would, for example, fclose(NULL) be well defined, I would not have problems in writing:

free(p);
fclose(f);

Which is something that happens very often when cleaning up things. Unfortunately, it seems strange to me to write

free(p);
if (f) fclose(f);

and I end up with

if (p) free(p);
if (f) fclose(f);

I know, it's not a rational reason but that's my case :)

If you rely on that free(0) is OKAY, and it's normal for your pointer to be null at this point, please say so in comment // may be NULL

This may be merely self-explanatory code, saying yes I know, I also use p as a flag.

there can be a custom implementation of free() in mobile environment. In that case free(0) can cause a problem. (yeah, bad implementation)

Related