Re: g_list_free()



On Wed, 26 Jan 2005, Maulet wrote:

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

No.

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 ]---

Here is a fixed version of your code:

#include <glib.h>

typedef struct Person_ Person;

struct Person_ {
    gchar *name;
    gint age;
};

void free_person (Person *p, gpointer unused)
{
    g_free(p->name);
    g_free(p);
}

int main (void)
{
    GList *list = NULL;
    Person *bush;

    bush = g_malloc(sizeof *bush);

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

    list = g_list_append(list, bush);

    /* do stuff with list, then... */

    g_list_foreach(list, (GFunc) free_person, NULL);
    g_list_free(list);

    return 0;
}

Allin Cottrell



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