Question

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?

Was it helpful?

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.

OTHER TIPS

Reading and writing a variable in the same statement is probably not a good idea.

Change this line:

        this->cur = this->cur->next = new Node;

Too

        cur->next = new Node;  // Add node
        cur       = cur->next; // Move end marker.

Also this is not needed.

        if(next)
            delete next;

Just do:

        delete next;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top