Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 701
yesraaj Avatar asked Mar 05 '09 15:03

yesraaj


People also ask

Do null pointers need to be deleted?

Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either. If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete at all.

Is it safe to delete a Nullptr?

In c++03 it is pretty clear that deleting a null pointer has no effect. Indeed, it is explicitly stated in §5.3. 5/2 that: In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.

Why do we set pointer to null after delete?

You should not write code that performs deletion of null pointer. If you use delete on uninitialized pointer, void pointer, then behaviour of program is undefined. Better practice is to stop using new & delete . This is C++ not Java & C#.

What is the purpose of a null pointer?

Commonly, the null pointer is used to denote the end of a memory search or processing event. In computer programming, a null pointer is a pointer that does not point to any object or function. A nil pointer is a false value. For example, 1 > 2 is a nil statement.


1 Answers

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

like image 197
Randolpho Avatar answered Sep 28 '22 18:09

Randolpho