user3663882
user3663882

Reputation: 7357

Deallocated objects with delete

What if we delete an object and then try to access an object through the pointer which has been deleted? I found the following:

Before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways

[...]

— the object will be or was of a class type with a non-trivial destructor and the pointer is used as the operand of a delete-expression,

But this's not exacly the case I'm looking for. What happend if the storage has been release or reused? Does standard explain that case?

Upvotes: 1

Views: 103

Answers (4)

sharptooth
sharptooth

Reputation: 170489

C++03 covers this in 3.7.3.2/4 (Deallocation functions). When the memory where the object was stored is deallocated all pointers to that memory get invalidated and after that they cannot be used - they cannot be dereferenced, cannot be cast (seriously!!!), cannot even be printed (no, not kidding), doing any of those yields undefined behavior. The only two things you can do to such pointers are either assigning them a null pointer or assigning them a valid pointer.

Upvotes: 2

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36391

If the memory has been released and then reallocated, then in theory there is no harm, but it is very unlikely that the reallocation will provide you a usable chunk of memory for your pointer type. Even if it will be the case, you will have strange/complex behavior because you pointer will see different objects (some kind of volatile objects ?).

I would certainly never rely on such a behavior, except if you need/want to manage the memory by yourself (with placement new for example)...

Upvotes: 3

Daniel
Daniel

Reputation: 235

If I understand your question correctly, you're wondering if information is still accessible, even after it has been deallocated?

I would say that there is no guarantee. After deallocation, anything stored on the stack is no longer protected. "Limited use" most likely refers to accessing immediately after deallocation. Even then, there is a risk of corrupted data and a segmentation fault.

I hope this answers your question.

Upvotes: 2

Vishal Kumar
Vishal Kumar

Reputation: 802

"Undefined behavior" must be answer from standard. But what ever standard says do not do this. It will get u only trouble with no gain :)

Upvotes: 6

Related Questions