Re: Memory question



David Rosal wrote:
Hello.

I know this is a general C programming issue, but...

It is a memory leak to call g_strdup() as argument to other function?

For example, if I do this:

gtk_entry_set_text(GTK_ENTRY(entry), g_strdup("banana");

Am I leaking memory?

AFAIK, the above code makes glib (via libc):
1) ask the kernel for a chunk of memory.
2) copy "banana" in that chunk.
3) pass the address of the chunk to the function gtk_entry_set_text().
But that address is lost, since we do not assign it to any pointer variable.
My question is: Is that memory chunk free'd before the program exits?

If a function takes ownership of a string that you pass to it
as a paramater, this should be explicitly documented and it definitly
is not standard behaviour.

This is also a good hint:

void       gtk_entry_set_text                   (GtkEntry      *entry,
                                                 const gchar   *text);

If the parameter is "const", then it definitly doesnt take ownership,
modify or free the string.

So the answer is yes, you are leaking memory.

Cheers,
                             -Tristan



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