Tuesday, April 21, 2009

Can you delete a NULL pointer?

What happens when you delete a pointer set to NULL in C++?

Thankfully, nothing! delete will check for a pointer being NULL and will skip deleting the object if it finds the pointer to be set to NULL.

So you dont have to do the following in your code:

if (ptr != NULL)
{
    delete ptr;
    ptr = NULL;
}

The check to see if ptr is null is redundant and can be removed.

But it is always a good idea to set your pointer to NULL after deleting it because delete does not set the pointer to NULL and calling delete twice on the same pointer can lead to BAD things happening. And what is worse is that multiple delete related bugs are extremely hard to debug and can cause your application to behave badly in totally unrelated sections of the code.

So always do this:

delete ptr;
ptr = NULL;

5.3.5 (6): If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

Working Draft, Standard for Programming Language C++http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2798.pdf

Now you know!

1 comment:

Unknown said...

alread put comment in two times