Is this code causing a memory leak?

I'm not sure if delete is actually de-allocating memory or if it's just calling next's destructor and re-pointing 'next' to nullptr.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

struct N
{
    int data;
    N* next;

    N(int d)
    {
        data = d;
        next = nullptr;
    }

    ~N()
    {
        delete next;
        next = nullptr;
    }

    void insert(int data)
    {
        N* temp = this;
        while(temp->next != nullptr)
            temp = temp->next;

        temp->next = new N(data);
    }
};

int main()
{
    N* n = new N(1);
    n->insert(2);
    n->insert(3);
    n->insert(4);
    n->insert(5);
    delete n;
}
Last edited on
No, it's not causing a memory leak. "delete" first calls the dtor and then deallocates the object when the dtor returns. It's probably not the most efficient way to deallocate a list, though, since if the list has a million members it sill stack up a million calls before finally popping back up through the call stack.
Last edited on
Thank you for the clarification. Is it possible to avoid the recursive stack with a singly linked list? Or would I have to make it doubly linked?
Yes, it's possible. See if you can figure out how to do it.
Singly or doubly linked has nothing to do with it.
The problem is calling delete in the dtor (which calls the next node's dtor, which calls the next, etc, until finally actually beginning to delete nodes on the way back up the call chain).
Overall, it would be best to have a List class that deletes the list in its dtor.
Another advantage of a List class is that it can have both a front and back pointer so that adding an element to the back of the list doesn't require traversing the entire list. It can also store the current size.
Last edited on
Topic archived. No new replies allowed.