I have a few global linked lists in my program, and a "generic" function that get a pointer to head, and free all nodes:
void freelist(list* head) {
list* tmp;
while (head != NULL) {
tmp = head;
head = head->next;
free(tmp);
}
}
function working good and in the end, the local pointer to the list (head),
became a NULL
. But a global pointer of the list doesn't changed to NULL
, and still points to the start of "empty" list (not my values, values after freeing).
Assuming your last node point to NULL and you need double pointer in freekist to make your global pointer NULL.
In other words if you want to change global head to NULL give the address of globalHead to freelist function, to do that you need double pointer.
You can make call to freelist like below.
freelist(&globalHead);
And your freelist definition goes like below.
void freelist(list **head)
{
list* tmp;
if(head ==NULL)
return;
while(*head!=NULL)
{
tmp=*head;
*head=(*head)->next;
free(tmp);
}
}