TheNotMe
TheNotMe

Reputation: 1058

The after-effects of deleting a pointer

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

Answers (5)

sharptooth
sharptooth

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

iammilind
iammilind

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

James Kanze
James Kanze

Reputation: 153899

p is a variable, right. So it's lifetime is determined at compile time, not at runtime.

Upvotes: 2

KBart
KBart

Reputation: 1598

What you have got here is called dangling pointer - a monster you normally would want to avoid at any cost.

Upvotes: 0

simonc
simonc

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

Related Questions