Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the pointer guaranteed to preserve its value after `delete` in C++?

Inspired by this question.

Suppose in C++ code I have a valid pointer and properly delete it. According to C++ standard, the pointer will become invalid (3.7.3.2/4 - the deallocation function will render invalid all pointers referring to all parts of deallocated storage).

At least in most implementations it preserves the value and will store exactly the same address as before delete, however using the value is undefined behavior.

Does the standard guarantee that the pointer will preserve its value or is the value allowed to change?

like image 409
sharptooth Avatar asked Feb 15 '11 09:02

sharptooth


People also ask

What happens to a pointer after delete?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).

Can I use a pointer after delete?

Yes, it's totally fine to reuse a pointer to store a new memory address after deleting the previous memory it pointed to.

Does delete destroy the pointer?

delete keyword in C++Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.

Does deleting a pointer make it null?

Deleting a pointer will do nothing if the pointer set to NULL. It might be the reason to check for the NULL pointer that deleting a pointer which is already set to NULL may indicate bugs in the program.


3 Answers

No, it's not guaranteed and an implementation may legitimately assign zero to an lvalue operand to delete.

Bjarne Stroustrup had hoped that implementations would choose to do this, but not many do.

http://www.stroustrup.com/bs_faq2.html#delete-zero

like image 74
CB Bailey Avatar answered Sep 18 '22 18:09

CB Bailey


If, for whatever reason, you want to be sure the pointer variable is not changed by delete, write:

delete p + 0;
like image 21
fredoverflow Avatar answered Sep 17 '22 18:09

fredoverflow


I believe that most implementations will keep the value, only for the sake of having no reason to change it. But regardless of whether the value is kept, it's still a useless pointer, is it not?

like image 22
Ken Wayne VanderLinde Avatar answered Sep 21 '22 18:09

Ken Wayne VanderLinde