Search code examples
c++memory-leaksshared-ptrdoubly-linked-list

Shared_ptr doubly linkedlist memory leak


I am getting some memory leak although using smart_ptr.

class linkedlist{
public:
    linkedlist(){}
 private:
    struct node{
        shared_ptr<node> prev{nullptr};
        shared_ptr<node> next{nullptr};
        int data;
    };
    shared_ptr<node> head{nullptr};
    shared_ptr<node> tail{nullptr};
 };

Solution

  • That's because this forms a cycle, which can't be dealt with by shared ptr.

    For example, with two nodes a and b in your list:

    {
        linkedlist l;
        {
            std::shared_ptr<node> a{new node};
            std::shared_ptr<node> b{new node};
            // a count: 1, b count: 1
            a.next = b;
            b.prev = a;
            // a count: 2, b count: 2
            l.head = a;
            l.tail = b;
            // a count: 3, b count: 3
        }
        // a count: 2, b count: 2  (local variables destructed)
    }
    // a count: 1, b count: 1 (l, l.head and l.tail destructed)
    // count != 0, so not deleted and memleak
    

    To fix this, have node.prev and linkedlist.tail be a std::weak_ptr to prevent nodes indirectly holding a strong reference to themselves through node.prev.next or node.next.prev