tags:

views:

1179

answers:

14

I just realized after years of writing C++, that I can safely delete a NULL pointer. So I figure, I'm not the only one that wasn't aware of this. Now I feel silly for all my

if(p) delete p;

code laying around.

Am I the only one that hadn't realized this? Or is it a less known feature of C++?

+12  A: 

A lot of C programmers don't realise that the same is true of malloc and free.

A more interesting question is WHY programmers (both C and C++) don't realise this - it is spelt out clearly in the reference section of K&R and on page 128 of Stroustrup.

anon
Yeah that's also true. But fortunately I did know that one :)
Robert Gould
I believe freeing null pointer should be avoid whenever possible.
claferri
In C, you surely would prefere testing the pointer for non null value and then call free rather then calling free everytime, function call are much more expensive then statement.
claferri
@claferri but the standard says its kosher... I agree with you, but I think we are wrong
Robert Gould
All free does is the same test that you would do, and function calls on modern hardware are not very expensive.
anon
@Robert why are we wrong?! A function call will always be more expensive than a statement and I believe the first thing free() does is to do the same statement before anything else !
claferri
I should also point out that all the if (ptr == NULL ) tests will bloat the code, leading to possible performance problems because of loss of locality.
anon
claferri: Almost everytime you're about to free a pointer it is != NULL. Cutting away that useless statement will actually improve performance in most cases. And if you free() that often in your program that it matters, probably you should improve elsewhere (better memory management).
ypnos
claferri. That won't make sense. C++ will call your delete operator with NULL either. so if you worry about those function calls (hell, why would you do), you would have to do it for C++ too.
Johannes Schaub - litb
or shall we rather say - the compiler is free to call your operator delete, and does so usually because that is the logical place to check for a null pointer and then return to do nothing.
Johannes Schaub - litb
@litb : I was only speaking about C. And I do worry about function calls when I'm looking for optimization (for example in HPC).
claferri
This all sounds like premature optimization to me, worrying about the cost of a null check or avoiding a function call when freeing memory. Writing clean code is more important 99% of the time, so in general, the null check should be dropped.
markh44
Steve Fallows
damn... nice page reference
anon
+1  A: 

Not sure about C++, but in Delphi you can call Free on a nil pointer and it causes no problems.

Despite that, I continue to check for nil/NULL, just as a sanity check.

Gamecat
in C++ its safe, just learned it today. And now I feel if(p) delete p is like if((1==1)==true) :/
Robert Gould
Good point. Time to teach this old dog a new trick.
Gamecat
+1  A: 

Yep.. one of the first things we learnt. No need to check for null when deleting. But if someone has already deleted the object and forgot to set the pointer to NULL, then you have a problem.

Gayan
Simple solution to this problem: use RAII and make it impossible to have deleted pointers hanging around.
Kaz Dragon
+16  A: 

In the beginning I didn't know. I learnt this after reading C++ FAQ Do I need to check for NULL before delete p?

It says that "The C++ language guarantees that delete p will do nothing if p is equal to NULL"

aJ
I read it in the linux manpage: http://linux.die.net/man/3/free -- it is missing in the BSD manpages.
ypnos
+7  A: 

Ho, yes i know that ...

But I spent a lot of time fighting with people who write their own "operator new / delete" without knowing that sort of thing : As they usually are of the bytes-and-processing-cycles-are-precious family they would rather sell their mother down the river than checking for NULL in every call of their precious "optimized" operator.

So it seems the books are not clear enough about it !

siukurnin
A: 

Kind of an odd question really. The cost of the 'problem' is not really that large.

Now one reason to-do it, is it allows you to call debugging commands that check for invalid pointers, or memory usage counting, etc

Simeon Pilgrim
+1  A: 

Another such nifty fact is that 'this' can equal NULL (although the standard stands it's an undefined behavior). For example:

MyClass *myob = NULL;
myob->myfun();

Inside myfun() 'this' pointer will equal NULL.

so what happens then ?
yesraaj
if it's a static function it should work. If you access class-members you'll dereference NULL, which crashes with an error message on all SDK's I've used...been there done that.
qwerty
If this will not be dereferenced inside myfun() and myfun() is not virtual, no error will occur. What C++ does is simple function call: myfun(myob). This is safe if myfun() is not virtual. If it's virtual, C++ will first dereference myob to obtain address of vtable, resulting in memory error.
None of this is true - you have undefined behavour, according to the C++ Standard.
anon
Wondering what if myfun is virtual?
It will cause a crash, as I mentioned in my previous comment. As Neil pointed out, according to the standard, calling a method on null pointer is an undefined behavior. My answer is therefore half-true.. However it's for sure educational and has real-life value ;)
A: 

yes i know... deleting a null pointer does not have any side effect. But i wonder why it is done in project I work

if(NULL != pSomeObject)//any reason for checking for null
{
 delete pSomeObject;
pSomeObject = NULL;//any reason for assigning null
}

is-there-any-reason-to-check-for-a-null-pointer-before-deleting

yesraaj
No reason, the result after the lines is the same.
xgoan
Well, maybe there's significant diffence between how long "assign null to null pointer" and "skip assignment in case of null pointer" take to execute, but without profiling this can't be determined. And a huge comment on why the check is done would be very useful for this code maintainers.
sharptooth
There is reason for assigning NULL. Wild pointer is the last thing you need.
EFraim
+9  A: 

Something similar, the new operator always returns a valid pointer, in other case it throws an exception, so very common code like:

MyClass *p = new MyClass;
if(!p)
   return;

doesn't make sense.

jab
that is another good "useless" tradition :)
Robert Gould
that code did make sense on old SO's like Windows 95, windows 98, etc.
Edison Gustavo Muenz
I don't think that is always true. If you are using (for some reason) certain older c++ implementations new doesn't throw. You could also use nothrow new (MyClass *p = new(std::nothrow) MyClass). Also, you could just override operator new.
KitsuneYMG
This code makes sense if you are compiling using VC6. Take a look at this question: http://stackoverflow.com/questions/550451/will-new-return-null-in-any-case
Naveen
Even on new versions of MSVC (and maybe others) you can set an option to not assert on failure of new but instead return null.
Greg Domjan
The code makes sense if you're working at Google: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml -- exceptions are not used in Google at all.
HMage
A: 

Safe operation of delete NULL doesnt payoff too much unless you normalize (set to NULL) already deleted pointers. Although its odd, in most cases i use self grown functions that look like this:

void DoDelete(void **p)
{
   if(! p || ! *p)
       return;
   delete *p;
   *p = NULL;
}

This is the only way to automatically avoid deleting a already deleted pointer. Of course this aint no use within a STL-Container or alike.

RED SOFT ADAIR
It isn't even valid C++ - deleting via a void * is undefined behaviour.
anon
You are right of course. This was only meant as pseudocode.
RED SOFT ADAIR
Luc Hermitte
+10  A: 

I estimate that about 1,200,000 people are aware of this, and the other 5,998,800,000 are still unaware.

Daniel Earwicker
Given that there were 333 views for this question when I added this coment, your numbers are now probably slightly off.
anon
The world population is estimated to be 6.77 billion as of April 2009, so if 1,200,000 people know it, there are 6,768,800,000 who don't :)
Daniel Daranas
Way to assume that the known humans on Earth constitute everything in existence that qualifies as "people". Speciesists.
chaos
+2  A: 

I only just found out about this yesterday, feel kinda dumb now

daz-fuller
welcome to the club :)
Robert Gould
A: 

In one project I work on the recommendation is to always check for NULL before calling free(). Yes, it's not needed according to the standard, but supposedly there are platforms out there where libc ties itself into a knot if you try to free a NULL pointer, and this particular project is portable to a plethora of platforms.

Though I have no idea if such platforms are actually used today, or if the rule is just some leftover from 20 years ago that nobody has bothered to update. Anybody know better?

janneb
+2  A: 

Am I the only one that hadn't realized this?

No. Probably, other people don't know it yet.

Or is it a less known feature of C++?

It's a basic piece of knowledge in C++. But, for some reason, a number of people have misconceptions about it.

Daniel Daranas