Search code examples
c++memorymemory-leaks

A question regarding a memory leak in a C++ program


I received this piece of code as an assignment and one of the questions was: Will there be a memory leak in the program because the destructor of MyList releases the nodes but not the data. Does the string class release the memory by itself when delete node is performed? And if the template variable is not a string or something else... In short, I can't understand if there is a problem here. What happens when the node memory is released?

template<class E> class MyList 
{
    class Node 
    {
        friend class MyList<E>;
        E data;
        Node* next = nullptr;
        ~Node() {  }
    };

    Node* head = new Node;
    Node* tail = head;
    Node* createNode(const E& data, Node* prev)
    {
        Node* node = new Node;
        node->data = data;
        node->next = prev->next;
        prev->next = node;
        return node;
    }
    public:
    MyList() = default;
    MyList(const MyList&) = delete;
    MyList& operator =(const MyList&) = delete;

    void push_front(const E& data) 
    {
        Node* node = createNode(data, head);
        if (tail == head) tail = head;
    }
    void push_back(const E& data)
    {
        tail = createNode(data, tail);
    }

    ~MyList() 
    {
        Node* node = head, * next;
        while (node != nullptr)
        {
            next = node->next;
            delete node;
            node = next;
        }
    }

    template<class Function>
    void apply(Function f)const 
    {
        Node* node = head->next;
        while (node != nullptr)
        {
            f(node->data);
            node = node->next;
        }
    }
};

int main()
{
    MyList<std::string>m3;
    m3.push_back("Hello");
    m3.push_back("World");
    MyList<MyList<std::string>*> m4;
    m4.push_front(&m3);
    m4.push_back(&m3);
    m4.apply([](auto plist)
    {
        plist->apply([](const auto& val) 
        {
            std::cout << val << std::endl;
        });
    });     
}

I can't figure out if when Node is released the features inside it are also released. I would appreciate an answer regarding this.


Solution

  • The destructor for the MyList class does not leak memory unless it is the responsibility of Node objects to own the data any pointer they may contain points to. A node's data member will be destroyed when the node is destroyed.

    Consider a case like MyList<int *> where each element in the list is a pointer to an int. We would not expect destroying the list to destroy the original int values the nodes' data members point to, especially as they may not have been dynamically allocated in the first place.