Remove NULL but not compile error

I am confused why the following C ++ code might compile. Why is the call to delete method 0 not an error ?!

int *arr = NULL; // or if I use 0, it the same thing delete arr; 

I tried to run it and it did not give me any error at all ...

+7
c ++ null
source share
5 answers

C ++ ensures that removing p does nothing if p is NULL.

For more information, see section 16.8.9 here :

+19
source share

You can remove the NULL pointer without any problems, and the error you may / may not have will be at compile time, but at runtime.

 int *ptr_A = &a; ptr_A = NULL; delete ptr_A; 

This is usually convenient to do:

 ... delete ptr; ptr = NULL; 
+1
source share

It is a de facto standard in C and C ++ (and not only in them) that resource reallocation procedures should take arguments with a null pointer and just do nothing. In fact, this is a pretty solid convention. So the real question here is: why does this surprise you? Why do you think this should lead to an error? Moreover, what makes you think that it should not compile ???

By the way, your question, as they say, does not seem to make much sense, since your code cannot actually compile. There is no type in the alleged pointer declaration that will cause any compiler to issue a diagnostic message.

+1
source share

NULL and 0 are not the same thing. In C ++ you should use 0.

There is nothing syntactically incorrect or ambiguous regarding deleting a null pointer. In fact, it is by definition non-op; that is, the operation to delete the 0th address is equivalent to doing nothing.

0
source share

Although your example is trivial, the compiler cannot know (at compile time) the value of the pointer.

At compile time, you can also dereference zero:

 // this code compiles Object* pObject = 0; pObject->SomeMethod(); 

Compilers are not designed to handle these types of errors at compile time.

And in most (all?) Implementations there is a "delete 0" as inoperative. This code should work fine:

 Object* pObject = new Object(); delete pObject; pObject = 0; delete pObject; 

Although I'm not 100% sure :)

0
source share

All Articles