Using GLib main loop to free up temporary memory



Greetings!

When you program with GTK+ (or GLib) with C, sometimes there's a need
for temporary dynamically-allocated variables. The problem is to free
them in the right time — or worse — having to use even more auxiliary
variables, like in the example below:

gchar *func(void) {
 gchar *temp = g_strdup("i am a temporary string");
 return g_strdup_printf("%s -> %f", temp, G_PI);
}

In this example, the temp variable will leak memory, since it was not
freed after g_strdup_printf. A way to fix this would be rewriting func
as:

gchar *func(void) {
 gchar *temp = g_strdup("i am a temporary string");
 gchar *temp2 = g_strdup_printf("%s -> %f", temp, G_PI);
 g_free(temp);
 return temp2;
}

Much better: temp won't leak anymore, but we had to use another
variable. I propose a simpler solution, but it requires that your
program runs in the GLib main loop. It should be used only on callback
functions and is not threadsafe. Include these two tiny functions in
your program:

static gboolean __idle_free_do(gpointer ptr) {
 g_free(ptr);
 return FALSE;
}

void gpointer idle_free(gpointer ptr) {
 g_idle_add(__idle_free_do, ptr);
 return ptr;
}

Now we can rewrite func as:

gchar *func(void) {
 gchar *temp = idle_free(g_strdup("i am a temporary variable"));
 return g_strdup_printf("%s -> %f", temp, G_PI);
}

This way the memory will be freed as soon as GLib gains control and
the main loop is ready to process events.

Use the code as you wish.


Cheers,

--
 Leandro A. F. Pereira <leandro tia mat br>
 Developer, Tiamat Software Wizardry.



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