I’m trying to delete all nodes of a singly-linked list in C with the following code.
void free_all(struct cd *head){
struct cd *tmp;
tmp = head->next;
while(tmp != NULL){
head->next = tmp->next;
free(tmp);
tmp = head->next;
}
free(head->next);
free(head);
head=NULL;
}
But if I print all elements of the linked list after that to check if the list is empty or not, the “head” element is always printed. So it looks like the head element isn’t being deleted properly. What’s wrong?
‘head’ is an function argument, with local scope. So although you set it to NULL at the end of the function, this will have no effect as the function just returns right after, moving that variable out of scope.
Whatever variable was passed in, will still point at the head of the list (though this memory has been freed, it likely still contains plausible data).
The head has been freed. It just doesn’t necessarily look that way, because you’ve kept a pointer to the memory where it used to live.
To fix it, simply null the pointer out after calling this function to free the list.
You could pass in a pointer to a pointer, in order to NULL the pointer within the function, but that seems overly complex for this situation.