Deleting a null pointer

user987280 picture user987280 · Nov 4, 2011 · Viewed 8.2k times · Source

Possible Duplicate:
Is there any reason to check for a NULL pointer before deleting?

I often see the following in code:

if(pointer)
    delete pointer;

To my understanding it is safe to delete a null pointer, so what is the point of this check?

Answer

AusCBloke picture AusCBloke · Nov 4, 2011

delete will check if the pointer is NULL for you, so you're right that the check isn't needed.

You might also see that some people set the pointer to NULL after it's deleted so that you don't do anything stupid like try and use memory that is no longer yours or stop you from deleting the pointer twice, which will cause an error.