打印

glib 编程问题

glib 编程问题

大家看看问题出在哪??
#include <glib.h>

typedef struct {
    gchar * name;
    gint shoe_size;
    gint age;
} Person;


int main(int argc, char** argv) {
    Person *fred = g_new(Person, 1);
    GList *list = NULL;

    gint num,i;
    gchar *ming[]={"aaa","bbb","ccc","ddd"};


    for ( i=0 ;i<4 ;i++)
    {
        fred->name = ming;
        fred->shoe_size = i+10;
        fred->age=60+i;
        list = g_list_append(list, fred);
    }


    num=g_list_length (list);

    for (i=0 ;i<num;i++)
    {
        g_print("%d '%s' %d  %d \n", i,
                ((Person *)g_list_nth (list,i)->data)->name,
                ((Person *)g_list_nth (list,i)->data)->shoe_size,
                ((Person *)g_list_nth (list,i)->data)->age);
    }



    g_print("long%d \n\n", num);
    g_list_free (list);
    g_free(fred);

    return 0;
}

结果:

0  'ddd' 13 63
1  'ddd' 13 63
2  'ddd' 13 63
3  'ddd' 13 63
long4

为什么都是ddd,请高手指点.

TOP

看看 国外论坛的回复
wrote:
>     for ( i=0 ;i<4 ;i++)
>     {
>         fred->name = ming;
>         fred->shoe_size = i+10;
>         fred->age=60+i;
>         list = g_list_append(list, fred);
>     }

You need to make a new Person each time. At the moment you are making a single Person, adding a pointer to it to the list, and overwriting the details next time around the loop.

You'll need to change the way you free the list too.

John
需要每次都要定义一个Person,而你只定义了一个,把指针append进
list ,并且在循环中被不断的复写。

This is a memory leak.  You still have person (one instance only) fred
allocated.  If you did this exercise right, and allocated a new Person
object for ever g_list_append, then you'd have 4 leaked person objects
at this point.   

Supposing you did allocate a new Person object for each list item, you'd
need to do this before the g_list_free call (I think):

g_list_foreach(list,g_free,NULL);

While C does require very manual tracking of memory allocation and
deallocation, the glib routines make it very easy to clean up after
yourself.  In fact many of the data structures, including the trees,
hashes, and so forth, allow you to assign "destructor" functions that
are called on each item in the structure when the structure is freed.
Using these wonderful routines, I create and destroy thousands of very
large and dynamic tree structures without a single memory leak.
Amazing.  I love glib!  I think it should be part of the standard C
library.

Michael

还是有差距!

TOP