2

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

};
Oleksiy
  • 37,477
  • 22
  • 74
  • 122
  • 4
    It will be hard to answer this with certainty without the definition of `Node` – Timothy Jones Aug 07 '13 at 06:04
  • 2
    @TimothyJones: I'll raise your "hard" to "impossible". – Mats Petersson Aug 07 '13 at 06:07
  • You'll crash if `head` is invalid, otherwise looks ok (assuming `Node::next` is always properly initialized). – Jonathan Potter Aug 07 '13 at 06:09
  • Destroying `int` obviously does not throw, but if you ever want generalize this to other types it would pay to be paranoid and update `head` before you start destroying nodes. You wouldn't want to leave an invalid pointer in `head` if the data destructor throws an exception. – Casey Aug 07 '13 at 06:21

1 Answers1

1

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.

Spook
  • 25,318
  • 18
  • 90
  • 167
  • In general I had an "if current! = this" before deleting and mark an error in case. – Galigator Aug 07 '13 at 11:47
  • What is the advantage to using the reference instead of the pointer? – gravitas Aug 07 '13 at 19:27
  • 1
    @RSinghS You cannot pass a null object, cannot pass immediate value (lvalue) and a lot more explicitly inform your source code reader, that you want to modify passed variable (it is not *that* obvious in case of a pointer). Read further: http://stackoverflow.com/questions/7058339/c-when-to-use-references-vs-pointers – Spook Aug 08 '13 at 05:46