Re: GtkLabel trouble #2



On 2001.05.10 14:05:37 +0200 Jered Bolton wrote:
> Original posting reproduce for context:
> 
> >Why is it that if I use gtk_label_get, I get a seg fault if I then try
> >and use gtk_label_set_text ?
> >
> >e.g. I want to get the text of a label and use the text to determine
> >whether I need to change the text of the same label:
> >
> >        gtk_label_get(GTK_LABEL(label_pointer), pText);
> >
> >        if ( pText contains something or other)
> >                  gtk_label_set_text(GTK_LABEL(label_pointer),
> >"something else...");
> >
> 
> 
> Furthermore, I found the following to be quite confusing:
> 
> This code works fine, without seg faulting:
> 
>   gchar *pText;
> 
>    gtk_label_get(GTK_LABEL(label_pointer), &pText);
> 
>   gtk_label_set_text(GTK_LABEL(label_pointer), "fred");
> 
> 
> BUT, this code does not:
> 
>   gchar **pText;
> 
>    gtk_label_get(GTK_LABEL(label_pointer), pText);
> 
>   gtk_label_set_text(GTK_LABEL(label_pointer), "fred");
> 
> 
> 
> 
> Subtly different, but why does one work and not the other?

This one is easy. It's an unallocated pointer.
See the difference:

char bla[256];
sprintf(bla, "blablabla");

and

char *bla;
sprintf(bla, "blablabla");

The first will work, the second segfault. That's because the second one is
a pointer, but a pointer to what? To nothing, it needs to be allocated (for
example by malloc():

char *bla;
bla = malloc(256);
sprintf(bla, "blablabla");

That will work.
Your *pText is a pointer, &pText will give an allocated pointer to this
pointer. **pText is a pointer which is not yet allocated yet so it refers
to nothing - which probably causes the difference.

I suppose that:
char **pText;
pText = malloc(1);
gtk_label_get(GTK_LABEL(label_pointer), pText);

will work.

Hope this makes things clear.

Ronald

-- 
---------------------------------------------------.
--   .-.    | Ronald Bultje                        |
--   /V\    | Running: Linux 2.4.4 and OpenBSD 2.8 |
--  // \\   | E-mail : rbultje ronald bitfreak net |
-- /(   )\  | WWW    : http://ronald.bitfreak.net/ |
--  ^^-^^   |    *** Warning: Unix Addicted ***    |
---------------------------------------------------'





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