Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: How to free nodes in the linked list?

People also ask

How do you free a node in a linked list?

To delete a node from the linked list, we need to do the following steps: Find the previous node of the node to be deleted. Change the next of the previous node. Free memory for the node to be deleted.

Do you have to free linked list?

For every malloc you will need a free otherwise you will leak memory. One possible way to analyze your program to see if you don't have memory leaks is to use Valgrind. Show activity on this post. For your first question, yes, you should walk the list and free each node.

How do you clear a linked list?

LinkedList clear() Method in Java LinkedList. clear() method is used to remove all the elements from a linked list. Using the clear() method only clears all the element from the list and not deletes the list.


An iterative function to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

What the function is doing is the follow:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

Simply by iterating over the list:

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

One function can do the job,

void free_list(node *pHead)
{
    node *pNode = pHead, *pNext;

    while (NULL != pNode)
    {
        pNext = pNode->next;
        free(pNode);
        pNode = pNext;
    }

}

struct node{
    int position;
    char name[30];
    struct node * next;
};

void free_list(node * list){
    node* next_node;

    printf("\n\n Freeing List: \n");
    while(list != NULL)
    {
        next_node = list->next;
        printf("clear mem for: %s",list->name);
        free(list);
        list = next_node;
        printf("->");
    }
}

You could always do it recursively like so:

void freeList(struct node* currentNode)
{
    if(currentNode->next) freeList(currentNode->next);
    free(currentNode);
}