开发者

Scanf fails with bus error

开发者 https://www.devze.com 2023-01-02 06:10 出处:网络
I\'m playing with C and I\'ve run into this error: #include <stdio.h&开发者_StackOverflow社区gt;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号