Search code examples
c++dangling-pointer

Clarify dangling pointer in C/C++


I'm little confusing about dangling pointer in C/C++

void remove(){
Node* curr = new Node(10);
Node* pt = curr;
delete curr;

// do something here
// do other thing here
}

I assume Node* pt is still dangling pointer before the function remove() is terminated?

I don't have to worry about the pointer Node* pt after remove() is terminated?


Solution

  • When you call delete curr, the value stored in curr is unchanged, but the memory at that location has been returned to the system.

    Lets walk your code line by line:

    Node* curr = new Node(10);
    

    for argument's sake, lets imagine that the memory allocated has address 0x1000, that means that curr now has a value of 0x1000.

    Node* pt = curr;
    

    pt now also has the value (points to location) 0x1000.

    delete curr;
    

    This returns the memory at location 0x1000 to the system. HOWEVER, at this juncture both curr and pt both still contain the value 0x1000.

    They are both dangling pointers.

    Dangling pointers are unavoidable when you use raw pointers, and they are not implicitly bad. You just have to be careful not to use a dangling pointer or return one.

    void badfunc() {
        char* p = new char[10];
        delete p;
        return p;  // use of dangling pointer
    }