Johnathan Gross
Johnathan Gross

Reputation: 678

What does a deleted pointer point to?

int*a=nullptr; //NULL before C++11
a=new int(1);
delete a;

What does a point to now? Does it point to nullptr or does it point to the address it was pointing to before it was deleted?

Upvotes: 6

Views: 1281

Answers (4)

M.M
M.M

Reputation: 141544

A few other answers incorrectly say "the value doesn't change". However it does: before the deletion it was valid, and after the deletion it is invalid; this is a change.

Further, the representation of the value may change too. For example the implementation could set a to be null, or some pattern that the debugger will recognize to help with detecting invalid uses of variables.

Upvotes: 6

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

According to the C++ Standard (6.7 Storage duration)

4 When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values (6.9.2). Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

So after this expression statement

delete a;

the value of the pointer a is not changed but has became invalid. Neither object exists at this address.

Upvotes: 5

Peter Ruderman
Peter Ruderman

Reputation: 12485

Don't confuse the pointer's value with what it points to. After the delete, the pointer's value is unchanged. It isn't set to nullptr or anything like that. The thing it points to is undefined. All to often, it ends up pointing to exactly what it did before, which leads to all manner of interesting bugs.

Upvotes: 4

David Schwartz
David Schwartz

Reputation: 182753

It doesn't point to anything. There is nothing useful you can do with its value now.

Upvotes: 4

Related Questions