Re: Memory question



David Rosal <david rosal upf edu> writes:

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?

You're passing the address of "text" to the function 
gtk_entry_set_text(). Next you g_free() that address, so AFAIK the 
memory manager marks it as free.
Isn't it dangerous? I mean, after g_free() any call that requests for 
memory (g_strdup, g_malloc, ...) can overwrite that memory chunk, 
changing the text in the GtkEntry. Am I right?

No.  gtk_entry_set_text() will keep its own copy of the text
internally, which is contained within the GtkEntry object.  Once you
set the text, you can safely free your copy.  If it didn't work this
way, you would quickly run into all sorts of memory leaks.


Regards,
Roger

-- 
Roger Leigh
                Printing on GNU/Linux?  http://gimp-print.sourceforge.net/
                Debian GNU/Linux        http://www.debian.org/
                GPG Public Key: 0x25BFB848.  Please sign and encrypt your mail.



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