I'm confused why the following C++ code can compile. Why does a call to delete the method of 0 not produce any error?!
int *arr = NULL; // or if I use 0, it's the same thing
delete arr;
I did try to run it, and it did not give me any error at all...
Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
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.
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.
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.
The C++ language guarantees that delete p will do nothing if p is equal to NULL.
For more info, check out Section 16.8,9 here:
You can delete a NULL pointer without problem, and the error you may/can have won't be at compilation time but at runtime.
int *ptr_A = &a;
ptr_A = NULL;
delete ptr_A;
Usually it's convenient to do :
...
delete ptr;
ptr = NULL;
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