Thread: need help freeing a linked list

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    14

    need help freeing a linked list

    Hi all,

    So, in general, freeing a linked list is pretty straight forward. my freeing function looks like this:
    Code:
    typedef struct node
    {
    	uint64_t digit;	
    	struct node *next;
    	struct node *prev;
    } node;
    
    void free_chain(node* hostage)
    {
    	node* tmp_pntr;
    	while (hostage)
    	{
    		tmp_pntr=hostage->next;
    		free(hostage);	//(!)
    		hostage=tmp_pntr;
    	}
    	
    	return;
    }
    However I want to optimise my code some, and don't want to have separate malloc calls for every node in a given list. However, the way the program runs, I may have a couple separate nodes followed by a bunch of nodes that are stored in a contiguous memory block that was malloced all at once. The problem is, of course, that the free_chain function will try to free each node individually, even if they were malloced as one chunk, and thus run into a double free problem. How do I get around this?

    Thanks so much!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Keep track of the memory ranges of the blocks, and if your pointer falls in that range, set it to NULL, and don't free it unless you would no longer have any valid pointers in that range.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Sep 2009
    Posts
    14
    ah, ok. that makes sense, thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Freeing a linked list -- possible bug.
    By msh in forum C Programming
    Replies: 5
    Last Post: 01-25-2011, 12:22 PM
  2. Freeing a linked list
    By Matty_Alan in forum C++ Programming
    Replies: 4
    Last Post: 04-17-2010, 11:19 PM
  3. Freeing Linked Lists
    By mrpickle in forum C Programming
    Replies: 4
    Last Post: 01-21-2004, 07:57 PM
  4. freeing linked lists
    By lambs4 in forum C Programming
    Replies: 1
    Last Post: 03-27-2003, 06:14 PM
  5. Freeing a linked list
    By CeeCee in forum C++ Programming
    Replies: 7
    Last Post: 02-02-2002, 05:59 PM

Tags for this Thread