delete [] and NULL

L

Lars Uffmann

dmparadiselm said:
It is guaranteed that a NULL pointer deletion is harmless in C++
standard.

@OP: However, as dmparadiselm pointed out, you really want to set your
pointers to NULL after deletion, for a
delete p;
might (will) wreak havoc on your program if p is not NULL but there is
no memory reserved anymore.

Best Regards,

Lars
 
L

Leandro Melo

But setting every deleted pointer to 0 doesn't solve real problems.

void f(void *ptr)
{
delete ptr;
ptr = 0;

}

int main()
{
int *ip = new int;
f(ip);
delete ip;      // double delete, despite setting ptr to 0
return 0;

}

But that's because what is passed to f() is a copy of the pointer. If
the pointer was passed by reference, the code would be ok. In this
case, I'm assuming (for clarity only) f() receives an int pointer
instead of a void pointer.

void f(int*& ptr)
{
delete ptr;
ptr = 0;
}

int main()
{
int *ip = new int;
f(ip);
delete ip; //Pointer was set to 0 in f. No double delete.
return 0;
}
 
K

Kai-Uwe Bux

Leandro said:
But that's because what is passed to f() is a copy of the pointer. If
the pointer was passed by reference, the code would be ok.
[snip]

The general problem is that multiple pointers to the same object might
exist. If you could guarantee that there is only one pointer to that
object, in general you might just avoid the pointer and put the object on
the stack. If you cannot guarantee that only one pointer to the object
exists, setting the one you delete to NULL buys you nothing (other than
possibly hiding a bug) since you could still have a double deletion with
the others.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,167
Messages
2,570,910
Members
47,453
Latest member
MadelinePh

Latest Threads

Top