Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
Johnathan Gross Avatar asked Nov 01 '17 19:11

Johnathan Gross


4 Answers

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.

like image 87
M.M Avatar answered Oct 14 '22 02:10

M.M


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.

like image 34
Vlad from Moscow Avatar answered Oct 14 '22 01:10

Vlad from Moscow


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

like image 28
David Schwartz Avatar answered Oct 14 '22 00:10

David Schwartz


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.

like image 34
Peter Ruderman Avatar answered Oct 14 '22 01:10

Peter Ruderman