Re: g_list_free()



Maulet wrote:

Hi,

Just wanted to know if g_list_free() frees the memory allocated "by hand" and attached to the list nodes.
For example:

---[ start code ]---

GList *list = NULL;
typedef struct {
   gchar *name;
   gint age;
} Person *bush;

bush->name = g_strdup ("George");
bush->age = 8;

list = g_list_append (list, (gpointer) bush);
g_list_free (list);
list = NULL;

---[ end code ]---

Is this a memory leak? In other words: does the above g_list_free() free the string allocated in bush->name ?

yep, that's a leak. how would g_list_free() know the layout of your struct? you should do something like:

g_list_foreach(list, struct_person_free, NULL);
g_list_free(list);

where struct_person_free() is a function that you need to write that takes a Person* and frees any data inside it, as well as the struct itself. see the glib API docs for the proper signature for the function, though i believe the first argument passed is the list data pointer (and thus, in your case, the Person* pointer).

   -brian

p.s. note that also you didn't allocate memory for the struct 'bush' itself, so that would give you a segfault. i don't think your typedef line is valid either, but i dunno. you can do some weird stuff in C sometimes.



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