1

After deallocating memory, I expect pointer to point to the memory which was deallocated. But it points to some different address. Why so?

#include <iostream>
#include <string>

using namespace std;

int main() {

    int* p = new int(4);
    cout << p << endl; //address here is xxx
    delete p;
    cout << p << endl; //I expect it to be same xxx, but it is yyy
    p = nullptr;
    cout << p << endl; //no question here
    system("pause");
    return 0;
}

So, what does exactly that yyy memory location means, why it is not xxx?

Eric Klaus
  • 923
  • 1
  • 9
  • 24
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/184783/discussion-on-question-by-eric-klaus-why-dangling-pointer-points-to-different-me). – Samuel Liew Dec 06 '18 at 02:41

1 Answers1

-1

Contrary to popular belief, pointers are not just numbers and you are inviting weird behaviour by trying to do things with a dangling pointer, not limited to dereferencing them.

Your reading of a pointer's value involves an "lvalue-to-rvalue conversion" and the standard has this to say about your antics:

Otherwise, if the object to which the glvalue refers contains an invalid pointer value ([basic.stc.dynamic.deallocation], [basic.stc.dynamic.safety]), the behavior is implementation-defined. [7.3.1/3])

This means that your assumption/premise is incorrect. Although we wouldn't expect nice simple variables like ints to change on their own, life is not that simple for all value types. The pointer is not a number; it is a pointer. You are asking your computer to tell you the address of an object that no longer exists. Per the passage above, it's pretty much allowed to do whatever it likes under those conditions.

Apparently your compiler has decided to take advantage of this rule to apply some optimisation and you've ended up with a "weird" result (or its delete implementation deliberately modified its argument to aid in diagnostics (or... (or... (or...)))).

I will say though that I've never personally witnessed this behaviour. Then again, I don't make a habit of observing dead pointers. :)

Rule of thumb: null it out immediately and never speak of it again.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055