Scanf fails with bus error
I'm playing with C and I've run into this error:
#include <stdio.h&开发者_StackOverflow社区gt;
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?
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.
As to what Bus error: 10
means:
SIGBUS (10) / Bus error 10 means a signal sent to an application if an attempts is made to access memory outside of its address space. This may be due to bad pointer that has an invalid address in it.
精彩评论