Re: Using GLib main loop to free up temporary memory

On Wed, 2007-01-03 at 13:02 -0200, Leandro A. F. Pereira wrote:

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);

That's - no doubt - faulty leaking code.

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

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

That's redundant code that tries to fix the faulty code, but it does a
poor work.

You can just do:

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

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.

AFAIK idle calls are thread safe.

 Include these two tiny functions in
your program:

static gboolean __idle_free_do(gpointer ptr) {
  return FALSE;

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

If it's a void function, it may return nothing.

Try to increase the output level of your compiler if it does not warns
you about this - as example -Wall.

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.

Please don't do that. The variable can be freed before the return value
is used.

Instead of all this, just free the allocated memory as soon as you use

gchar *var = g_strdup_printf("i am a temporary string -> %f", G_PI);
g_print("%s\n", var);
g_free (var);


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