Search code examples
c++dynamic-memory-allocation

How does this work? Pointer to pointer assignment


#include <iostream>
using namespace std;
int main() {
    int *p1;
    p1 = new int;
    int *p2;
    p2 = new int;
    p2 = p1;    // what happens here?
    *p1=5;
    cout << "pointer 2 is " << *p2 << endl << *p1 << endl;  // both give out 5
    delete p1;  // what happens to p2 ?
    cout << "pointer 2 is " << *p2 << endl;
    delete p2;
    return 0;
}

What happens when I delete the pointer object p1? What is pointer p2 referencing now ? Can some one explain ? Thanks for the help


Solution

  • What is pointer p2 referencing now ?

    Nothing. It's dangling. It was pointing to the same thing p1 was pointing to, but you've deleted that.

    Consequently, your *p2 is broken, as is your delete p2; these both have undefined behaviour.

    You've also leaked the second new int, because p2 used to point to it but stopped doing so when you wrote p2 = p1 (you changed it to point to the first new int instead, like p1 does), and there's no other way to refer to it.

    Crude diagram of what happens in the OP's code, with respect to pointers