views:

72

answers:

1

I'm playing with C and I've run into this error:

#include <stdio.h>
int main ()
{
 char* foo;
 scanf("%s", foo);
 printf("entered %s", foo);
 return 0;
}

scanf takes pointer, foo is pointer, yet I get bus error. How can I make it work?

+4  A: 

You never initialize foo, so it points to a more or less random location in memory. Either allocate it on the stack.

char foo[10];

Or malloc it on the heap:

char *foo = (char *)malloc(10 * sizeof(char));

But if you malloc, don't forget to free().

And watch out for buffer overflows; if something takes in a buffer but no maximum size, be very careful. You can specify a maximum length for scanf by doing %9s, for instance. scanf will not account for the terminating null, though, so you need to pass one less than the length of your buffer.

Matti Virkkunen
Note also that you *must* allocate enough space to store the string read in by scanf. If you allocate only one character, you will get undefined behavior (likely a segfault) if you type in anything but the empty string.