Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading