我在使用 C 和 scanf
函数时遇到了这个我似乎无法弄清楚的奇怪错误。给定以下代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a;
} sample;
void fn(sample *s) {
char command;
scanf("%[abc]", &command);
printf("Read: %c\n", command);
printf("In the sample function:, %i\n", s->a);
}
int main() {
sample *s = malloc(sizeof(sample));
s->a = 4;
printf("Before sample function: %i\n", s->a);
fn(s);
printf("After sample function: %i\n", s->a);
return 0;
}
好像是段错误。随着输出:
$ ./sample
Before sample function: 4
a
Read: a
In the sample function:, 4
Segmentation fault (core dumped)
我使用了 gdb 并将一个 watch
附加到该结构,似乎在 scanf
函数内部,它似乎“修改”了该结构?这很奇怪,因为即使在示例函数“fn
”中的 scanf
之后,它也能够很好地打印出结构字段。但是,一旦从 fn
返回并跳回 main
,它会在尝试打印相同信息时出现错误?
有趣的是,如果您将 scanf
更改为 scanf("%c\n", &command);
(没有字符集),它似乎工作正常。作为记录,我使用的 gcc 版本是 4.7.2,我正在编译代码:gcc -O0 -o sample sample.c
。
我唯一的想法是,也许 gcc 不支持字符集?我不确定。只是想知道是否还有其他人可以解决这个问题?
最佳答案
scanf("%[abc]", &command);
写入一个字符串而不是单个字符。字符串的尾随空字符被写入程序中的 &command + 1
。
你应该传递给 scanf
像这样:
command
command
为:
char command[2];
关于c - GCC `scanf` 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17005460/