Re: Memory question



On Wed, 28 Sep 2005, David Rosal wrote:

Allin Cottrell wrote:

gchar *text = g_strdup_printf("banana %d", i);
gtk_entry_set_text(GTK_ENTRY(entry), text);
g_free(text);

Is the above code really safe?

Yes! A function such as gtk_entry_set_text() is bound to make a copy of the string offered by the caller. Or at any rate it is bound _not_ to attempt to free that string.

Think about it: suppose you pass gtk_entry_set_text() a string literal:

gtk_entry_set_text(GTK_ENTRY(entry), "foo");

If gtk tried to free "foo" you'd get an immediate crash, since this is not storage obtained via malloc. So we can infer that gtk (which is designed by wise and sane coders!) will not attempt to free strings that we pass into such functions.

So we can further infer that it is our business as callers of gtk functions to free strings that we pass to such functions, if we created these strings via functions that allocate storage -- i.e. that directly or indirectly call the C library function malloc() -- e.g. g_strdup(), g_strdup_printf() and friends.

Allin Cottrell



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