GTK+ FAQ
<<< Previous | About GLib | Next >>>

# Memory does not seem to be released when I free the list nodes I've allocated

GLib tries to be "intelligent" on this special issue: it assumes that you are likely to reuse the objects, so caches the allocated memory. If you do not want to use this behavior, you'll probably want to set up a special allocator.

To quote Tim Janik:

"If you have a certain portion of code that uses *lots* of GLists or GNodes, and you know you'd better want to release all of them after a short while, you'd want to use a GAllocator. Pushing an allocator into g_list will make all subsequent glist operations private to that allocator's memory pool (and thus you have to take care to pop the allocator again, before making any external calls): "

    GAllocator *allocator;
    GList *list = NULL;
    guint i;

    /* set a new allocation pool for GList nodes */
    allocator = g_allocator_new ("list heap", 1024);
    g_list_push_allocator (allocator);

    /* do some list operations */
    for (i = 0; i < 4096; i++)
      list = g_list_prepend (list, NULL);
    list = g_list_reverse (list);

    /* beware to pop allocator befor calling external functions */
    g_list_pop_allocator ();
    gtk_label_set_text (GTK_LABEL (some_label), "some text");

    /* and set our private glist pool again */
    g_list_push_allocator (allocator);

    /* do some list operations */
    g_list_free (list);
    list = NULL;
    for (i = 0; i < 4096; i++)
      list = g_list_prepend (list, NULL);

    /* and back out (while freeing all of the list nodes in our pool) */
    g_list_pop_allocator ();
    g_allocator_free (allocator);

<<< Previous | Home | Next >>>
How can I use the doubly linked lists? | Up | Why use g_print, g_malloc, g_strdup and fellow glib functions?