Re: GtkLabel trouble #2



On Thu, May 10, 2001 at 02:16:50PM +0200, Ronald Bultje wrote:
> 
> 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);

That's all correct, except for this part. Firstly, pointers take alot more than 1 byte, you'd at least want to malloc (sizeof *pText);
Secondly, mallocing and freeing is expensive and unwieldy, if the variable is only going to be used by the function (and whatever the function calls), it's much nicer to allocate the variable on the stack. That is to say, the char *pText;gtk_label_get (label, &pText) approach.

> 
> will work.
> 
> Hope this makes things clear.




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