Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete NULL but no compile error

Tags:

c++

null

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...

like image 787
cplusplusNewbie Avatar asked Oct 13 '09 03:10

cplusplusNewbie


People also ask

What happens if you delete null?

Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.

Is it OK to delete Nullptr?

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.

Do you need to delete null pointer C++?

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.

Do I need to check for null before delete p?

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.


2 Answers

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:

like image 157
Jacob Avatar answered Sep 30 '22 17:09

Jacob


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;
like image 25
Vincent B. Avatar answered Sep 30 '22 16:09

Vincent B.