Bwawhwmopoloin
Bwawhwmopoloin

Reputation: 91

Is my linked list implementation leaking memory?

Code:

struct LinkedList {
    int someData;
    LinkedList* next;

    LinkedList() : next(0) {}
    ~LinkedList() {delete next;}
};

void someFunction() {
    LinkedList list;

    list.next = new LinkedList;
    list.next->next = new LinkedList;
    list.next->next->next = new LinkedList;
    // And so on...
}

Am i correct to say that this code does not leak memory? When list scopes, it should call its destructor, which calls the destructor of next, which calls the destructor of next, and so on, until delete 0 is called.

Upvotes: 3

Views: 225

Answers (2)

gsamaras
gsamaras

Reputation: 73366

If you call delete as many times as new is being called, then you are fine. In this case, this happens.

If you are in the current node, then you should keep a pointer to the next one, and then delete the current one.

See an example I have in List (C), where you can "think" malloc() as new and free() as delete.

Upvotes: 0

Christophe
Christophe

Reputation: 73366

No your code doesn't leak memory. When list goes out of scope, it'll be deleted, and the chain reaction will delete every next element until the last.

However, your code doesn't respect the rule of 3. So as soon as you will copy construct or copy assign a LinkedList, its next pointer will get shallow copied. The first of the two copies that get deleted/destroyed will delete it. The other then works with a pointer that is no longer valid and will sonner or later delete it as well, causing UB.

Upvotes: 5

Related Questions