Linked List Delete List

I'm working on a linked list and was wondering how this looks to everybody else for a deleteList function.

1
2
3
4
5
6
7
8
9
10
11
12
13
void deleteList(Node* head)
{
    Node* iterator = head;
    
    while (iterator != 0)
    {
        head = iterator->next;
        delete iterator;
        iterator = head;
    }
    
    delete head;
}
Looks reasonable enough, although line 12 is unnecessary since both iterator and head must be null when that line is reached.

That makes sense. Although, if I had a line after a call to this function that says
delete head;
I get a malloc error. Why do I not get an error at line 12??
I'm still not sure why I would get a malloc error outside the function but not inside. However, since head was a part of main I needed to change my deleteList function's parameters to pass the Node* by reference so that head ends up as a NULL pointer upon completion of the function.
void deleteList(Node*& head)

Once all of these are member functions of a class the pass by reference will not be needed.
On line 12, head is null.

In the calling code, head still points to the same place. Only a copy of the pointer is sent to deleteList. The fact that it is referred to by a variable of the same name is coincidental.
Last edited on
@cire, Thanks, that was what I figured out when I was testing it. So delete head on line 12 doesn't throw a malloc because it is a null pointer??
Correct. It is perfectly safe to delete a null pointer.
Topic archived. No new replies allowed.