Search code examples
c++inheritancememory-managementsegmentation-faultpolymorphism

Are there any issues from both the child and parent destructors being called when a derived object is destroyed?


If I have the below two classes:

#include <cstdlib>

class Parent
{
    protected:
        int* mem = (int*) std::malloc(5); // pointer to dynamically-stored object
    public:
        Parent() {};
        virtual ~Parent()
        {
            delete(mem);
        }
};

class Child: public Parent
{
    public:
        Child() {};
        ~Child()
        {
            delete(mem);
        }
};

int main(void)
{
    Child* c = new Child();
    delete(c);
}

Shouldn't calling delete on an instance of the Child class cause a segmentation fault, since the parent's destructor is also automatically called after the child destructor? And if so, would the solution be for the Child class to only deal with freeing dynamically-allocated memory "owned" by Child class (i.e. not delete mem in Child's destructor and leave it to Parent to deal with it) ?

I ran my main function and expected a segmentation fault to occur since mem was being freed twice - once in Child's destructor and again in the Parent destructor. No error occurred, which I found surprising. Can anyone please explain why?


Solution

  • Your code has 2 issues:

    1. Memory allocated with malloc should be released with free, not with delete.
    2. The Child should not attempt to free memory that it did not allocate. When the Parent destructor will execute it will attempt to release memory that was already released by the Child.

    Both these issues cause UB (Undefined Behavior), meaning anything can happen.