Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of a deleted pointer address

(*) As far as I know the Standard allows an implementation to modify the operand of the delete operator, however most implementations do not do that.

int* ptr = new int(0);
delete ptr; //delete is allowed to modify ptr, for example set it to 0
std::cout << ptr; // UB?

Acknowledging (*), is the reading of ptr (in the form of printing it) well-defined?

If delete does modify ptr, is it allowed to set a trap value, which would make reading ptr UB?

like image 270
PoweredByRice Avatar asked Apr 20 '17 01:04

PoweredByRice


People also ask

What does a deleted pointer point to?

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. "After the delete, the pointer's value is unchanged." That's not guaranteed.

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.

What does deleting a pointer mean?

Deleting a pointer (or deleting what it points to, alternatively) means delete p; delete[] p; // for arrays. p was allocated prior to that statement like p = new type; It may also refer to using other ways of dynamic memory management, like free free(p); which was previously allocated using malloc or calloc.

What happens if you delete pointer twice?

If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.


1 Answers

In C++14 this is implementation-defined behaviour, [basic.stc.dynamic.deallocation]/4:

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value, the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage.

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.

There is a footnote:

Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.

This changed since C++11 where the bolded text said "undefined behaviour" and there was no footnote.


So to answer your question, delete ptr; is allowed to set a trap value that would cause a runtime fault for std::cout << ptr. The compiler documentation must specify the behaviour. This is a narrower restriction than UB in which case any unstable behaviour would be permissible.

like image 63
M.M Avatar answered Sep 29 '22 14:09

M.M