Scanf因总线错误而失败

Mik*_*ite 0 c pointers scanf bus-error

我正在玩C,我遇到了这个错误:

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

scanf取指针,foo是指针,但我得到总线错误.我怎样才能使它工作?

Mat*_*nen 8

你永远不会初始化foo,因此它指向内存中或多或少的随机位置.将它分配到堆栈上.

char foo[10];
Run Code Online (Sandbox Code Playgroud)

或者在堆上malloc:

char *foo = (char *)malloc(10 * sizeof(char));
Run Code Online (Sandbox Code Playgroud)

但如果你是malloc,别忘了free().

并注意缓冲区溢出; 如果有东西需要缓冲但没有最大尺寸,请小心.您可以指定一个最大长度scanf%9s,例如.scanf但是,不会考虑终止空值,因此您需要传递一个小于缓冲区长度的空值.