skevthedev skevthedev - 1 month ago 14
C Question

Using a function to free a linked list with double pointer

I am having a tough time deleting all members in a linked in a single function. If I break it up like you see below, it works fine, but this seems wildly inefficient and want to figure out the correct way to do this. in order to free all nodes I need to have function to first free all nodes other then the head, then have a function free the head link. this seems like it would be easy to do but I am having trouble.

Thanks for the help!

int main() {

struct node *head = NULL;
createList(&head);

//do stuff with list

freeListMembers(head);
freeListHead(&head);

return 0;
}

int createList(struct node **head) {
//create list
return 0;
}

void freeListMembers(struct node *head){
while(head->next != NULL){
head->next = NULL;
free(head->next);
}
return;
}

void freeListHead(struct node **head) {
*head = NULL;
free(*head);
return;
}


here is the code that I want to work but does not. the issue I am seeing is a an error for "*head->next;" where it sais "expression must have pointer to struct or union type"

int main() {

struct node *head = NULL;
createList(&head);

//do stuff with list

freeAllListMembers(&head);

return 0;
}

int createList(struct node **head) {
//create list
return 0;
}

void freeAllListMembers(struct node **head){
while (head != NULL) {
struct node *temp = *head->next;
free(*head);
*head = temp ;
}
return;
}

Answer

From your code :

void freeListMembers(struct node *head){
    while(head->next != NULL){
        head->next = NULL;
        free(head->next);  
    }
    return;  
}

This is freeing NULL, not your node*.

Freeing the list is as simple as using a temporary pointer to the next node.

while (head) {
    node* next = head->next;
    free(head);
    head = next;
}

From your edit :

void freeAllListMembers(struct node **head){ 
    while (head != NULL) {
        struct node *temp = *head->next;
        free(*head);
        *head = temp ;
    }
   return;  
}

There are a couple errors with this. It should be while (*head != NULL) and (*head)->next. The first is a logic error, because head will always be non-NULL, and the second is a syntax error, because you need to dereference the head pointer before accessing the next pointer.