Is it safe to delete a NULL pointer?
And is it a good coding style?
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.
It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.
A NULL pointer doesn't allocate anything.
Because a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash.
delete
performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete
(helps avoiding double deletion and other similar memory corruption problems).
I'd also love if delete
by default was setting the parameter to NULL like in
#define my_delete(x) {delete x; x = NULL;}
(I know about R and L values, but wouldn't it be nice?)
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