Why is there memory leak when base class constructor is being called?

virtual destructor c++
derived class destructor c++
how to test destructor c++
pure virtual destructor
c++ call base class destructor
c++ destructor order
deleting object of polymorphic class type
does delete call destructor

I am practicing some inheritance and virtual destructors and i keep getting problem with exception being thrown after running my code, where child class destructor works properly but superclass destructor just wont work properly.

I suppose that i have a few misconceptions about destructors since every time i saw virtual destructors, command 'delete' was used outside of destructor actually, but, if i do that, then, what is the point of creating destructor?

#include <iostream>


template <class T>
class List
{
protected:
    T *data;



public:
    List()
    {

        data = new T[5];
        std::cout << "List constructor!";
    }


    virtual void putIn()
    {
        for (int i = 0; i < 4; i++)
            std::cin >> data[i];
    }
    virtual void printOut()
    {
        for (int i = 0; i < 5; i++)
            std::cout << data[i] << std::endl;
    }
    virtual ~List()
    {
        delete[]data;
        std::cout << "List destructor!";
    }


};


template <class T>
class League : public List<T>
{
public:
    League()
    {

        data = new T[5];
        std::cout << "League constructor!";
    }


    virtual void putIn()
    {
        std::cout << "Enter your values:\n";
        for (int i = 0; i < 5; i++)
            std::cin >> data[i];
    }
    virtual void printOut()
    {
        std::cout << "Your values are:\n";
        for (int i = 0; i < 5; i++)
            std::cout << data[i] << std::endl;
    }


   ~League()
    {
        delete[]data;
        std::cout << "League destructor!";
    }

};



int main()
{
    List<char> *p;
    League<char> leag;

    p = &leag; 

    p ->putIn();


    getchar();
    getchar();




}

Everything works just fine, but when program finishes, it says that exception is thrown it points to the base class destructor. Any help appreciated!

The problem is that data get deleted twice, first in ~League() and then in ~List(). Remove delete from ~League().

Then there is a problem of memory leak. League is not responsible for List::data but it initializes it. This causes a memory leak, because previous value will be lost and will not be deleted, ever. So don't set a new value in League, and use some other way to tell List to change the value, and then only List is responsible for its member, and would have to delete[] the old one before setting a new one.

C++ Virtual Destructors: How to Avoid Memory Leaks, How to avoid memory leaks with virtual destructors when using inheritance in C++. For instance, consider a pointer to a base class (such as PayOff) being then the base class destructor will be called instead of the derived class destructor. This is no problem, but worse is that the destructor for class MyClass is not being called at all. Valgrind therefore reports the memory for first A instance as leaked. By the way, the destructor for the MyClass instance is intentionally not being called as the object hasn’t been fully constructed and logically never existed.

The summary of the crash is: When a derived class is destroyed, it's destructor is called, and then it's based class destructor is called. The derived destructor is calling delete[]data; and then the base class is calling delete[]data; a second time, which is undefined behavior. Luckily, in this case, it resulted in a crash, so you knew to look for it.

The idea is that the base class owns the data pointer, and so the base class should be the one to delete it. The derived class doesn't own the pointer, and so should not be deleting it.

Due to this misunderstanding, Dialectius also observed a memory leak. When the League is constructed, the List constructor is called first, which allocates memory, and then the League constructor is called, which allocates different memory, leaking the first bit of memory. Again, the derived class doesn't own the pointer and should probably not be touching it. The derived class should ask the base class to modify the pointer.

It's also worth mentioning that your classes violate The Rule of Three and so you should add copy constructors and copy assignment operators to keep the class safe.

Memory Leak In Cpp, This, however, has a memory leak because destructors are never called if the class MyClass : public BaseClass { }; // with 't' moved into BaseClass // and an exception in a constructor, data members that have already been constructed will​  Memory leak only occurs if you've not deleted the memory before the end of the program executes. Ensure you've deleted all new values. If you're reallocating memory, keep an eye on each memory and ensure it is deleted when no longer used.

Why do I need child destructor then ?

Like Dialecticus said you don’t need it in this situation. Suppose that you want to keep backup of your array then you’ll have another dynamic templated field in child class like T *childData. Now it’s good idea to use child class’ destructor.

Why does the base class need to have a virtual destructor here if the , I get that class base's implicit destructor is being called instead of derived's, but I don't get why that's a problem here. If I were to write an explicit  If the object that the pointer is pointing to is deleted, and the destructor is not set to virtual, then the base class destructor will be called instead of the derived class destructor. This can lead to a memory leak. Consider the following code: class Base { public: Base(); ~Base(); }; class Derived : public Base { private: double val; public: Derived(const double& _val); ~Derived(); } void do_something() { Base* p = new Derived; // Derived destructor not called!! delete p; } What is

C++ In a Nutshell: A Desktop Quick Reference, If the object is being created as part of a new expression, and an exception is thrown, Note that if auto_ptr<> were not used, the class would have a memory leak and base-class destructors are called in reverse order of their constructors​. you suspect, if you create a 'base' then you get a memory leak because the memory allocated by "new someclass()" and "new int()" is never freed. The best solution is to design your class to not 'new' things. I guess you are coming from Java or something like that by your code stype. In C++ you rarely need to have classes that 'new' their members.

Introduction to C++, How does the compiler know to call the right destructor? derived class won't be destroyed properly, possibly resulting in memory leaks or other Instead, we have to arrange a way for the base class destructor to determine whether it's being  This, however, has a memory leak because destructors are never called if the constructor throws an exception. This seems to imply that if you do any resource allocation in your constructor at all then you must not allow any exceptions to be thrown. It is true that base class destructors are called. That means that the following doesn't leak:

Testing Object-oriented Systems: Models, Patterns, and Tools, can be and by how it can become an obstacle to people getting their work done |Dr Dobbs 98). The memory leak problem is not a problem exclusive to C​++. The use of assertions in base classes, constructors, and destructors is recommended to fragment, only Base: :~Base is called upon the deletion of Derived. They have a Class_Initialize event that is the constructor and a Class_Terminate that is the destructor. You can define properties and methods. I believe VBA uses reference counting for object lifecycle. Which is why you see a lot of Set whatever = Nothing in that type of code. In your example case I think it will not leak any memory.

Comments
  • You're violating The Rule of Three, but that's not actually the source of the bug.
  • Make data private - protected data memebers are always a problem, as you have found.
  • If you had made data private, you would not be able to delete it twice.
  • If you have a delete in the destructor, then you must ensure that you do not have a default copy constructor and/or a default assignment operator, as this can copy the pointer and you will have double frees. And you should only delete pointers you own. But modern c++ code you should not use delete and new anyway.
  • As for the deletes in the destructors, the key notion here is ownership -- who is the owner of data, and, hence, who is responsible for managing its lifetime? Since it's a member of List, the obvious owner is List. The destructor for List should delete it, and derived classes should not. They can look at it and what it points at, but should not try to manage its lifetime.
  • Why do i need child class destructor then?
  • In this example you don't need it. Remove it. Do you want to make an example where you do need a destructor?
  • Actually, i tried, and i thought that this is one of those, however, i was wrong, and i can't think of any examples where destructor in child class is needed.
  • Suggesting examples is not in the scope of Stack Overflow site. new and delete should be already very rarely used in modern C++ (there are std::shared_ptr and std::unique_ptr that take care of allocation and deallocation for you). A league is not a list anyway. It may contain a list of some sort (so a member of the League class would be some List), but it is not a list on its own. But, to give an example anyway, there could be players and referees in this league, all of them employees. All employees have a salary, but only players can have a club affiliation.
  • I'll keep that in mind and i will try to improve this code based on your comment. Thanks for your effort, i appreciate it!
  • but then, what is the point of derived-class destructor if it is not going to delete it? I could then create only regular base class destructor the usual way, right?
  • @cdummie: Correct: Since your derived class owns no resources, there's no reason for it to make have a destructor. Since your base class is designed to be inherited from, its' best to mark it's destructor as virtual, even if it's empty.
  • @cdummie See the Rule of Zero for a more general case of "If you don't have to do anything, do nothing."