Re: [Anjuta-list] tutorial problem



Quoting Kyle Davenport <kdd quickening hn org>:

> ok, I'll admit it.  Even tho I have been programming for 24 years, I'm a
> newbie to gnome programming.  I naturally took the plunge starting with the
> tutorial by Ishan Chattopadhyaya.   I followed the helloworld example to
> the letter and altho it would build, it crashed every time I ran it and
> clicked "OK".  WTF?  How could this be bad?:
> 
>         void 
> 	on_BT_OK_clicked (GtkButton *button, gpointer user_data) 
> 	{ 
> 
> 		GtkWidget *entry = lookup_widget (GTK_WIDGET(button), "ENTRY"); 
> 		GtkWidget *msgbox = gnome_app_new("Hello World", "Hello World"); 
> 		gchar *text1, *text2; 
> 
> 		text1 = gtk_entry_get_text (GTK_ENTRY(entry)); 
> 		text2 = strcat ("Hello, ", text1); 
> 		gnome_app_message (GNOME_APP(msgbox), text2); 
> 
> 	} 
The problem occurs because strcat doesn't allocate any memory. The prototype is
char *strcat(char *dest, const char *src);
So you were trying to append text1 to a constant string "Hello" which is not
allowed as it's read-only.

> Hours later I localized it to the strcat function, and nothing I could do
> to the variables or replacing strcat with sprintf or whatever would stop it
Using sprintf, would also require you to allocate some memory.

> crashing. If I just used text1 in gnome_app_message or defined text2 as a
> constant character string it would work.   Finally I thought of a
> "gnome-way" solution.  I used g_strconcat instead of strcat, and that
> worked fine.   Here's my replacement code:

> 
> void
> on_BT_OK_clicked                       (GtkButton       *button,
>                                                          gpointer        
> user_data)
> {
> 		GtkWidget *entry = lookup_widget (GTK_WIDGET (button), "ENTRY"); 
> 	        gchar *text1 = "Hello,"; 
> 		gchar *text2 = gtk_entry_get_text (GTK_ENTRY(entry));
> 
> 		text1 = g_strconcat (text1, text2, NULL);
> 	        GtkWidget *msgbox = gnome_app_new("Hello World", "Hello World");
> 		gnome_app_message (GNOME_APP(msgbox), text1); 
> }
> 
> Pretty discouraging for a beginner!  I'd still like to know what caused the
> problem.

This code works because g_strconcat allocates enough space for the new string
and then concatenates the strings.

Dan





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