[Glade-users] Problems with lookup_widget()



On Tue, 2005-05-10 at 17:14 +0200, Magnus Wirström wrote:
I have now found out that my problem occurs after i call a function i wrote, 
I am a novice in this so i might have done something stupid then i wrote it. 
It works as it intended but after calling it crashes the app at the next 
lookup_widget i use. Segment fault (11) is the result of the crash. here is 
the function:

char*
getcat        (GtkWidget *button)
{
      char *buffer;
      GtkWidget *entry_widget;
      gchar *string;
      
      entry_widget = lookup_widget(GTK_WIDGET(button), "comboboxentry1");
      string = gtk_combo_box_get_active_text((GtkComboBox*)entry_widget);
      
      strncpy(buffer,string,6);
      
      return(buffer);
}

Anyone see an error ??

Yes; read the documentation of strncpy. The important detail: "... the
destination string dest must be large enough to receive the copy."

It needs an allocated area to copy into, but you're giving it some
random uninitialized pointer rather than a pointer to some memory it's
allowed to scribble in, and as a result, it's scribbling on top of some
random spot in memory, causing a seg fault.

You should allocate an appropriately-sized chunk of memory (I guess in
this case, 7 chars since you only want the first 6 chars, and I assume
you still want it to be NULL-terminated)

So for instance:

char*
getcat  (GtkWidget *button)
{
        char *buffer;
        GtkWidget *entry_widget;
        gchar *string;

        entry_widget = lookup_widget(GTK_WIDGET(button),
"comboboxentry1");
        string = gtk_combo_box_get_active_text(GTK_COMBO_BOX
(entry_widget));

        buffer = g_new0(char, 7);
        strncpy(buffer,string,6);

        return(buffer);
}

Of course, that means that whatever called getcat() is now responsible
for freeing this newly allocated string.

You should also probably look into why you're supposedly passing in some
"button" and then always looking up "comboboxentry1" (Your code also
doesn't show where your newly created comboboxentry gets registered so
that lookup_widget can find it, but that's presumably handled elsewhere,
otherwise you'll have OTHER issues when you try to call
gtk_combo_box_get_active_text on some invalid pointer; I swapped your
cast to GTK_COMBO_BOX(entry_widget) since that helps to catch things
like that)





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