Search code examples
c++linked-listraii

Linked List RAII code inside destructor crashes


I'm trying to create a linked list within RAII spirit and I'm getting crashes inside a destructor where I call the destruct of an object of the same class. I get a stack overflow but only if the linked list is filled up to some number. Code:

struct Node
{
    static int created,deleted;

    Node* next;
    Node () : next(NULL) { created++; }

    ~Node()
    {
        deleted++;

        if(next)
            delete next;
    }
};

int Node::created = 0;
int Node::deleted = 0;

class LL
{
    Node root;
    Node* cur;

    public:

        LL() : cur(&root) { }

        void add()
        {
            this->cur = this->cur->next = new Node;
        }
};

Now, this code does NOT crash:

{
    LL l;

    for(int i=1;i<=1000;i++)
        l.add();
}

printf("Created %d, Deleted %d\n",Node::created,Node::deleted);

But this one does:

{
    LL l;

    for(int i=1;i<=5000;i++)
        l.add();
}

printf("Created %d, Deleted %d\n",Node::created,Node::deleted);

Why does it crash and how should it be fixed?


Solution

  • Let's try this again.

    In the destructor of Node you delete the pointer, which calls the destructor of the next Node, etc. This occurs recursively. You're simply running out of stack space.