Search code examples
c++dangling-pointer

Danglings Pointers and Delete Command in C++


I noticed something very strange in my C++ code.

class A
{
    public:
    void doIt(){cout<<"hello"<<endl;}
};
int main() {
    A* a=new A();
    A* b=a;
    delete a;
    b->doIt();
    return 0;
}

I thought that delete will erase the memory from the heap and b->doIt() would fail. But while running this code it works and even print "hello".

Why?


Solution

  • I thought that delete will erase the memory from the heap

    The only way you can "erase" memory is with a hammer.

    The memory is marked as "unused" and the object is destroyed, semantically.

    and b->doIt() would fail

    Why's that?

    There is no mechanism in place to do that for you, nor can there be one in the general case.

    It's your responsibility not to call functions on objects that don't exist.

    Speaking practically, it doesn't crash here because nothing in doIt actually attempts to access the object's memory. Remember, the function isn't stored "in" the object — it's part of your program, and your program still exists.

    Even if doIt accessed and/or mutated the object's state, as long as that memory were still in the active page, you'd probably still not get a crash. This is precisely why undefined behaviour is defined to be unpredictable.

    Avoid.