Re: GSList Keeps losing its contents



"Ian Frawley" <ifrawley opaltelecom co uk> writes:

Is what you saying that I should take a copy of my group GSList? If that's
the case will that not still be a pointer to my actual group list (pointer
to pointer) therefore having the same effect as my current code? I am sorry
if it is a silly question but I am not totally clued up on GSLists &
GLists.

A GSList is one link in a linked list, so what you have looks like
this:

        struct ScreenControl {
                GSList *sc_group;
                ...
        }

Where you have [something like, you can check exactly what it looks
like in the GLib source yourself]:

        struct GSList {
                gpointer data;
                GSList *next;
        };

The sc_group is a pointer to the first element of a linked list.  Each
element of such lists points to the next element in the list, except
the last one, which has a NULL pointer in it's next field. 

So your list looks like this:

        ---   ---           ---
        |1|-->|2|--> ... -->| |->NULL
        ---   ---           ---
        ^
        |
        sc_group

What you did was updating the sc_group pointer until it became zero,
but at that point you have no way of ever finding out what was in the
first element of the list, so your entire list was leaked and the
sc_group was a NULL pointer, i.e., an empty list.

What I suggest you do is to create a new pointer to your list
elements:

        new_list_pointer
        |
        V
        ---   ---           ---
        |1|-->|2|--> ... -->| |->NULL
        ---   ---           ---
        ^
        |
        sc_group

and then do use that pointer to refer to the elements of the
list. This way, the sc_group won't be updated, so it won't become
NULL. You can do this with something like

        GSList *list;
        for (list=sc_group; list != NULL; list = list->next)
        {
                /* use list->data here */
        }

which is a pattern you will see again and again in C programs.

If you already know about linked lists, then the above should be
trivially obvious, but if you don't, I'll suggest you read an
introductory book about programming.  I can't recommend any off-hand,
though.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]