This came up as one of the code review comments.
Is it a good idea to check for NULL before calling delete for any object?
I do understand delete operator checks for NULL internally and is redundant but the argument put forth was delete as an operator can be overloaded and if the overloaded version doesn't check for the NULL it may crash. So is it safe and reasonable to assume that if and when delete will be overloaded it will check for the NULL or not? In my understanding its reasonable to assume the first case that overloaded delete shall take care of the NULL check, and the review point doesn't hold good. What do you think?
There is no reason to check for NULL prior to delete. Assigning NULL after delete might be necessary if somewhere in the code checks are made whether some object is already allocated by performing a NULL 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.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.
C++ Junkie Simple answer is YES. It is perfectly safe to delete a null pointer. In C++ delete operator is used to deallocate the memory block pointed by the pointer by releasing the memory allocated via new operator.
No, don't check for null. The standard says that delete (T*)0;
is valid. It will just complicate your code for no benefits. If operator delete
is overloaded it's better to check for null in the implementation of the operator. Just saves code lines and bugs.
EDIT: This answer was accepted and upvoted, yet, in my opinion, it was not very informative. There is one missing piece in all answers here, and, for conscience sake, let me add this last piece here.
The standard actually says in [basic.stc.dynamic], at least since C++03:
Any allocation and/or deallocation functions defined in a C++ program, including the default versions in the library, shall conform to the semantics specified in 3.7.4.1 and 3.7.4.2.
Where the referenced sections, as well as some other places in the standard listed in other answers, say that the semantics of passing a null pointer are a no-op.
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