Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a null pointer [duplicate]

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?

like image 906
user987280 Avatar asked Nov 04 '11 03:11

user987280


People also ask

What happens if you delete a null pointer?

What happens when delete is used for a NULL pointer? Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.

What happens if you delete a pointer twice?

If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.

Can you delete a null ptr?

Yes it is safe. There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.

Is it fine to call delete twice for a pointer?

Is it fine to call delete twice for a pointer? Explanation: It is undefined behavior to call delete twice on a pointer. Anything can happen, the program may crash or produce nothing.


2 Answers

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.

like image 189
AusCBloke Avatar answered Sep 28 '22 09:09

AusCBloke


While it is safe now, it wasn't always :-) so it's likely habitual. Also there are other consequences to delete. 1) if you are using a specialized memory manager and overriding new and delete operators, then you may very well have to do a check Operator Delete for more details

like image 31
Ahmed Masud Avatar answered Sep 28 '22 09:09

Ahmed Masud