c - GCC `scanf` 段错误

标签 c gcc struct scanf

我在使用 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/

相关文章:

c++ - 在 scientific linux 6 上安装 gcc 4.8 时出错

C 结构体指针的理解

c++ - 调用drawow会导致堆损坏

Coverity和 "Failed to initialize ICU, try using the --prevent-root option"

c++ - C++ 中的编译问题 (CodeBlocks 13.12)

c++ - 我怎样才能初始化这个结构?

json - 我可以在 Swift 中声明一个名为 'Type' 的变量吗?

c++ - 对 c 结构进行排序

c - C的数据流和控制流程图

c++ - 将 C/C++ 代码从 Linux 转移到 Windows 真的很慢