Re: Memory question

Am Mittwoch, den 28.09.2005, 21:44 -0400 schrieb Allin Cottrell:
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);

Is the above code really safe?

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.

Let's investigate a few common C pointer argument conventions:

1 foo (const void *bar);

means that bar will definitly not be modified. While the foo author
could theoretically force to free it would require casting the const
away and whoever does it is on crack:
C uses call by value. So after invoking foo, which could do free ((void
*)bar), and set its local local copy of bar to NULL, the outer bar
variable is undefined. Using it futher will most likely result in a
crash, including calling free (bar); in the outer frame again.

2 foo (void **bar);

This is some sort of call by reference. You pass the address of the bar
variable, i.e. char *foobar = ...; foo ((void **) &foobar); This syntax
ensures that the foo function can dereference its local copy of &foobar,
and make *bar (which is foobar) point to NULL after freeing, or
reallocate it - do all the pointer magic (except for pointer arithmetic,
because it is a void * pointer in this case).

3 void * foo (void *bar);

is just a variant of 3. It will also work on the local copy of bar, and
- if it changes bar - return that changed value. So you can invoke it
like char *foobar = ...; foobar = foo (foobar);.

I've never seen any function acting like that, to be honest.

4 void * foo (const void *bar);

Just some flavor of 3, which will always return newly allocated memory
in addition to that already allocated for bar, while not modifying the
eel_str_strip_chr [1] uses this variant.


Christian Neumair <chris gnome-de org>

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