Re: OT: Problems with strings



Magnus Wirström wrote:
Hi.

I'm a newbie so please don't fry me :)
I have a strange problem (at least i think it's strange ;) ). In my app i set up a gchar like this

	gchar *post;

	entry_widget = lookup_widget(GTK_WIDGET(button), "text_bolag");
	buffer = gtk_entry_get_text(GTK_ENTRY(entry_widget));
	strcpy(post,buffer);
	memset(buffer,0,100);

When i run it I get segmentation fault and the debugger tell me this error.
post		(gchar *)0x12 <Address 0x12 out of bounds>

What could generate a such runtime error ? I have no idea why i get this and it have been working before. I'm thankful for any suggestion.

If you wanna more info please email me.

It seems you are a newbie to C. I suggest you to borrow a few books about C from your local library.

Let us take a look at this piece of code:
> 	strcpy(post,buffer);

The function strcpy copies the content of 'buffer' into the memory block pointed to by 'post'. However, 'post' is uninitialized, so it doesn't point to any memory block! (or actually, it points to random, uninitialized garbage memory blocks that you cannot use, because it's uninitialized).

You must first allocate memory:
post = malloc(100);
strcpy(post, buffer);

However, there are problems in this example! What if 'buffer' is larger than 100 bytes? You will get memory corruption. (in this case, it's a buffer overflow, so it's a security bug!) There are two ways to solve the problem.
1. Find out how much memory you need, and allocate that much.
   gchar *post;
   int len;
   ...
   len = strlen(buffer);
/* We allocate len+1 bytes, because strlen() returns the length of the string, excluding the trailing NUL */
   post = malloc(len + 1);
   strcpy(post, buffer);

2. Use strncpy(), which puts a limit into how many bytes it will copy at most.
   post = malloc(100);
/* Fill the entire memory block full of zeroes. If 'buffer' is longer than 99 bytes then this ensures that 'post' is correctly NUL-terminated. */
   memset(post, 0, 100);
   strncpy(post, buffer, 99);


I hope you've learned from what I wrote.

But, there is a much simpler solution to your problem. You just want to duplicate a string. In that case, use strdup() (or the glib equivalent: g_strdup()):

gchar *post;

entry_widget = lookup_widget(GTK_WIDGET(button), "text_bolag");
buffer = gtk_entry_get_text(GTK_ENTRY(entry_widget));
post = g_strdup(buffer);
memset(buffer,0,100);
/* Don't forget to free 'post' when you don't need it anymore */



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