Thread: freeing list

  1. #1
    Unregistered
    Guest

    freeing list

    ok, lets say i have a funtion that gets nodes for a link list from a malloc'ed/calloc'ed block of structs. lets also say that the function exhaust several blocks. after im finished doing whatever with the list, how do i free all the nodes. i dont think i could just traverse the list freeing each node because id end up freeing addresses that have already been freed (i think). i thought maybe i could either store the beginning address of each block allocated on a stack then traverse through that or maybe i could free the first node in the list, go down BLOCKSIZE nodes, free and repeat until end of list but im not sure which would be the best way to do it. im not even sure if thats the way it should be done.
    id really appreciate it if you guys could help me out with this. thanks in advance.

  2. #2
    This is the way I would take care of it:

    Code:
    void clear (nodePtr *front)
    {
       nodePtr lptr = *front;   /*make lptr point to frist node in list*/
       nodePtr tptr = NULL;   /*tptr points to NULL*/
    
       while(lptr != NULL)   /*while the list is not empty*/
       {
          tptr = lptr;            /*move tptr up 1 node*/
          lptr = lptr->right;  /*move lptr up 1 node*/
          freeNode(tptr);     /*free node tptr points to*/
       }
    
       *front = NULL;        /*assign head to NULL, making list empty*/
    }
    I'm sure there are other ways to do it, but this is the easiest way I found.
    DrakkenKorin

    Get off my Intarweb!!!!

  3. #3
    Unregistered
    Guest
    im allocating memory for a block of structs and retrieving nodes from that. i dont think i can simply traverse the list freeing each node as i could if i had just allocated mem one node at a time. thanks anyway.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  2. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  3. Linked List
    By jpipitone in forum C Programming
    Replies: 4
    Last Post: 03-30-2003, 09:27 PM
  4. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 06:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM