Thread: free linked list

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    380

    free linked list

    How do I free a linked list and would the code below be the answer to my question?

    Thank you

    Code:
    struct node {
     int data;
     struct node* next;
    };
    
    int main()
    {
     struct node* head = NULL;
     struct node* second = NULL;
    
     head = malloc(sizeof(struct node));
     second = malloc(sizeof(struct node));
    
     head->data = 1;
     head->next = second;
    
     second->data = 2;
     second->next = NULL;
    
     free(head);
    
     return 0;
    }
    Don't you dare hit me on the head, you know I'm not normal.
    A Stooge Site
    Green Frog Software

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Remember that everything you malloc(), you must free(), so given this rule, it's clear that your program doesn't do the job.

    For a linked list, you should traverse the list, free()'ing each node as you go.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    380
    For a linked list, you should traverse the list, free()'ing each node as you go.
    Then does this code accomplish that problem?

    Code:
    struct node* current = head;
    while(current != NULL)
    {
        free(current->next)
        current = current->next;
    }
    Don't you dare hit me on the head, you know I'm not normal.
    A Stooge Site
    Green Frog Software

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Code:
    struct node* current = head;
    while(current != NULL)
    {
        free(current->next)
        current = current->next;
    }
    No, this has a nasty bug. Once you free() memory, you shouldn't reference it again. So in your example, you free()'d the next node, and then pointed to it.

    Try something like this:
    Code:
    struct Node *Current = Head;
    struct Node *tmp;
    
    while (Current)
    {
    	tmp = Current->Next;
    	free(Current);
    	Current = tmp;
    }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help sorting a linked list. Beginner
    By scarlet00014 in forum C Programming
    Replies: 1
    Last Post: 09-27-2008, 06:16 PM
  2. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  3. Adding directory/file names to a linked list
    By thoseion in forum C Programming
    Replies: 13
    Last Post: 12-08-2006, 01:13 PM
  4. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 02:48 PM