Oleksiy
Oleksiy

Reputation: 39850

Am I safely deleting a linked list?

Just want to know if there are any flaws/inconsistencies/memory leaks in this implementation of deleting a linked list:

// Function to delete the entire linked list
void deleteList(Node** head) {

    Node* current = *head;
    Node* next;

    while (current != 0) {

        next = current->next;
        delete current;
        current = next;

    }

    *head = 0;
}

Edit:

struct Node {

    int data;
    Node* next;
    Node(int data) : data(data){}

};

Upvotes: 2

Views: 146

Answers (1)

Spook
Spook

Reputation: 25927

It would be more C++ if you passed head pointer by reference, not by pointer:

void deleteList(Node * & head)
{
    // (...)

    head = nullptr; // NULL in C++ pre-11
}

Also, to keep code a little more tidy, you can move declaration of next inside the loop:

while (current != 0) 
{
    Node * next = current->next;
    delete current;
    current = next;
}

My only worries about memory leak would concern properly freeing node's contents, but since you store a simple int, there shouldn't be any problems there.

Assuming, that your list have valid pointers to nodes and that head pointer is valid too, everything else seems fine.

Upvotes: 1

Related Questions