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?
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.
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.
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? Explanation: It is undefined behavior to call delete twice on a pointer. Anything can happen, the program may crash or produce nothing.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With