Leon Breedt wrote:

> i'm working on a doubly-linked list at the moment, just one or two questions:
> 
> i looked at the way the doubly linked list is implemented in glib,

What is glib?

> and it 
> seems to me a way to create a list is to not call plist_alloc() explicitly, 
> but use plist_append(), and have that do the allocating.  and, so far, it
> works.  
> 
> now, my question:  should i free() the data items in the list cleanup code, or 
> leave that to the part of my program where i allocated the data items? i.e.
> in the part where i allocated the data items, iterate through the list and
> free() all my data items?  that seems to me the more logical approach. 
> (i.e. when *data is not a pointer, but for example a static struct that i added
> by calling plist_append(list, &struct_name);

In general, it's a bad idea to mix dynamically allocated data with
statically allocated data in complex structures. It means that you
can't just write a free_list() function; the code which frees the list 
has to know which pointers it can call free() on.

> i think this code is working, because i can successfully traverse the list
> forwards and backwards.
> 
> heres part of the code:

[snip]

> PList*   plist_append(PList *list, ppointer data)
> {
>    PList *new_item, *last_item;
> 
>    new_item = plist_alloc();
>    new_item->data = data;
> 
>    if (list) {
>       last_item = plist_last(list);
>       last_item->next = new_item;
>       new_item->prev = last_item;
>       return list;
>    } else return new_item;
>                                        
> }

When working with linked lists, it is more usual (and quicker) to
insert at the front of the list, e.g.

PList* plist_prepend(PList *list, ppointer data)
{
   PList *new_item;

   new_item = plist_alloc();
   new_item->data = data;
   new_item->next = list;
   if (list)
     list->prev = new_item;

   return new_item;
}

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to