Kiran's Blog

Ramblings from a dehydrated mind…

  • Archives

    • 14,897

Deleting a NULL pointer..

Posted by kiraninbng on June 29, 2006


Whats wrong with the below code,

void CTestDelDlg::OnOK()
{
    CTry* pTry = NULL;
    delete pTry;
}

Nothing, except the function is pointless and without any logic.The point is that deleting null pointer will not throw an exception.If the pointer is NULL/0 delete assumes that allocation or new has failed.The C++ language guarantees that delete p will do nothing if p is equal to NULL.

The best way of deleting a pointer is to call delete first and set the pointer to NULL. delete. 

Ex :

void CTestDelDlg::OnOK()
{
    CTry* pTry = new CTry;
    delete pTry;
    pTry = NULL;
}
For more info on delete chk out http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/express_29.asp

Advertisements

One Response to “Deleting a NULL pointer..”

  1. Farpointer said

    Yes deleting a null pointer is not a big deal ,but u need to ask the implementor of the class wether he has overloaded the new operator :).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: