Search code examples
c++pointersmemorysmart-pointersdangling-pointer

Null dangling pointers c++


I have a pointer to an abstract class object ptr1. I need to create another pointer with the same adress ptr2 so that when you free and zero the ptr1 pointer, the ptr2 also becomes zero.

SomeObject* ptr1 = new SomeObject();
SomeObject* ptr2 = ptr1;

delete ptr1;
ptr1 = nullptr; // after that ptr2 should be nullptr

I know that it's dangling pointers problem and it can be solved with smart pointers but I want to solve it without them. Thanks in advance for your help!


Solution

  • Declare ptr2as a reference or pointer to ptr1, i.e. one of the following:

    SomeObject* &ptr2 = ptr1;
    
    SomeObject** ptr2 = &ptr1;
    

    By only having one instance of the pointer and ensure that this is only passed around by references or pointers to the pointer instance, you ensure that there cannot exist outdated copies of the pointer.