tags:

views:

255

answers:

9

Possible Duplicate:
Does free(ptr) where ptr is NULL corrupt memory?

Why do I keep seeing this code?

Actually I personally wrote this type of code, and I must say that I'm not sure why either :-D Maybe I just saw it somewhere.

Is there any platform that actually fails on free(0);?

+11  A: 

Many people just do not know that free(NULL) is permitted by the standard.

Tronic
See also http://stackoverflow.com/questions/1025589/setting-variable-to-null-after-free
Morgaelyn
+1  A: 

This is supported by the standard. Check out this SO answer to the question which essentially quotes ISO-IEC 9899.

Jacob
+1  A: 

Well, free(0) should do nothing in case of NULL argument, but still i remember having problems. I guess it was some old BCC.

Roman D
+1  A: 

Yes it is safe to free a NULL pointer. It allows you to do:

free(p) 

Instead of

if(p)
 free(p);

There is no benefit to calling free(0); directly.

Brian R. Bondy
+1  A: 

I have a fuzzy recollection of using the idiom to squash over-zealous compiler warnings ("warning: pointer may be null at this line ....").

That doesn't defend the practice, but it does in applicable circumstances explain it.

Will
+3  A: 

There's a good write up about this at: http://www.winehq.org/pipermail/wine-patches/2006-October/031544.html

Basically as long as your not running on 3BSD then free(NULL) is ok.

Douglas Leeder
+1  A: 

Even if it is allowed, it's completely useless. A pointer not being NULL does not imply that it points to a non-freed memory.

Try:

while (x) free(x);

:-)

cadrian
A: 

It may be supported by the standard now, but that doesn't mean it's supported by all compilers on all systems. And it didn't used to be supported by the standard.

I remember back in the day having all kinds of problems with programs crashing when I tried to free a NULL pointer. if(p) free(p); Would often be all it took to fix the crash. Of course, it didn't solve the source of the bad pointer, just prevented the program from crashing on error.

These days free(NULL) is widely supported, and the if(p) is no longer necessary. Even if you do find your program crashing on invalid pointer data, I'd say let it. Invalid pointers indicate a problem that won't be fixed by simply not trying to free them. Better to find and fix the source.

Daniel Bingham