Dvir Samuel
Dvir Samuel

Reputation: 13

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?

Upvotes: 0

Views: 52

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

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.


Upvotes: 4

Jakub Zaverka
Jakub Zaverka

Reputation: 8874

It is most likely because doIt method doesn't use any internal state of the A class. Compiler therefore probably optimised it to a static method and the call is invoked in a static class context. The fact that the pointer is dangling then do not prevent the method from being run.

However, it is undefined behaviour and more strict compilers might actually produce a code that indeed fails.

Upvotes: 1

Related Questions