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

yesraaj picture yesraaj · Mar 5, 2009 · Viewed 33.9k times · Source

I often see legacy code checking for NULL before deleting a pointer, similar to,

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

Is there any reason to checking for a NULL pointer before deleting it? What is the reason for setting the pointer to NULL afterwards?

Answer

Randolpho picture Randolpho · Mar 5, 2009

It's perfectly "safe" to delete a null pointer; it effectively amounts to a no-op.

The reason you might want to check for null before you delete is that trying to delete a null pointer could indicate a bug in your program.

Edit

NOTE: if you overload the delete operator, it may no longer be "safe" to delete NULL