Reputation: 1058
Object *p = new Object();
delete p;
When I delete p, the object allocation on the heap is deleted. But what exactly happens to p itself? Is it deleted from the stack? or is it still in the stack and still contains the address of the memory that previously held Object?
Upvotes: 3
Views: 279
Reputation: 170469
The pointer variable persists but its value is rendered invalid - doing anything with it except assigning another valid pointer or a null pointer yields undefined behavior. There's no guarantee the pointer value is unchanged.
Upvotes: 0
Reputation: 69978
When you perform delete p
. The memory pointed by p
is deleted.
delete
~= destructor + deallocation
Here delete
is just a term which states that the memory is released. There is no impact on total amount of memory of OS or the variable p
itself. p
still points to the memory which is now reclaimed by the system, and thus becomes a dangling pointer.
Upvotes: 0
Reputation: 153899
p
is a variable, right. So it's lifetime is determined at compile time, not at runtime.
Upvotes: 2
Reputation: 1598
What you have got here is called dangling pointer - a monster you normally would want to avoid at any cost.
Upvotes: 0
Reputation: 42165
p
is still on the stack and holds the address of the Object
you've just deleted. You are free to reuse p
, assigning it to point at other allocated data or NULL
/ nullptr
.
Upvotes: 8