tags:

views:

163

answers:

6

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?

+7  A: 

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

Tom
+1 This is what I remember but I couldn't find the reference to it.
Matt Davis
As I understand it, this flaw existed in some compilers even after standardization.
Michael Burr
It was always there, even in the original UNIX implementation. This is mentioned in P.J. Plauger's article on the standardisation process - can't find exact reference at this moment though.
anon
THe day that Joel is quoted as a technical authority is a sad one for the human race.
anon
Neil: this is quote from the forum on joel website, actual quote not from him but someone named Guidii. so i think human race has been saved today
zaharpopov
A: 

http://www.owasp.org/index.php/Double_Free ?

as far as I understand it, calling free() more than once on the same pointer (without that pointer being set to NULL/0) can lead to interesting stuff.

just somebody
how is it relevant to my question?
zaharpopov
ah, you're right, i misread the question, sorry
just somebody
+3  A: 

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 :)

Remo.D
A: 

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.

Pavel Radzivilovsky
+2  A: 

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.

anon
A: 

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

sevity