简体   繁体   中英

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){}

};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM