Re: Memory question



Am Mittwoch, den 28.09.2005, 10:58 +0200 schrieb David Rosal:
Colossus wrote:
Am I doing the same ( memory leaking ) with g_strdup_printf ?

Yes, of course. It also allocated new memory for you, but additionally
merges the ith (where ith > 1) argument of the g_strdup_printf into the
string as it encounters positional parameters ("%d", "%s", etc.). You
should really read a good C book, preferably the K&R, to grasp the
printf syntax.

If so what is the better way to write the following code: ?

response = ShowGtkMessageDialog (GTK_WINDOW 
(MainWindow),GTK_DIALOG_MODAL,GTK_MESSAGE_ERROR,GTK_BUTTONS_OK,
        g_strdup_printf ("%s",g_strerror(errno)) );
        return;

gchar *msg = g_strdup_printf("%s", g_strerror(errno));
response = ShowGtkMessageDialog(GTK_WINDOW(MainWindow), 
GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, msg);
g_free(msg);
return;


Uhm doing g_strdup_printf ("%s", string); doesn't have any advantage
over g_strdup (string);. It is more expensive however, because it has to
parse "%s". Because g_strerror returns a const char * (meaning that you
may not/can't/don't have to free it, since your app doesn't own the
memory), you can simply call

ShowGtkMessageDialog (GTK_WINDOW (MainWindow),
                      GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR,
                      GTK_BUTTONS_OK,
                      g_strerror (errno));

without leaking anything.

-- 
Christian Neumair <chris gnome-de org>


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