GCC`scanf`分段故障

mfj*_*nes 3 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;
}
Run Code Online (Sandbox Code Playgroud)

这似乎是错误的.随着输出:

$ ./sample
Before sample function: 4
a
Read: a
In the sample function:, 4
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

我用了gdb并附加了一个watch结构,看来在scanf函数内部,它似乎在"修改"结构体?这很奇怪,因为即使在scanf示例函数内部' fn'之后,它也可以打印出结构字段.但是,一旦从fn跳回到跳回main,它会在尝试打印出相同的信息时出现故障?

有趣的是,如果您更改scanfscanf("%c\n", &command);(没有字符集)它似乎工作正常.为了记录,我使用的gcc版本是4.7.2,我用以下代码编译代码:gcc -O0 -o sample sample.c.

我唯一想到的是gcc可能不支持字符集吗?我不确定.只是想知道是否有其他人可以解决这个问题?

oua*_*uah 6

scanf("%[abc]", &command);

写一个字符串而不是一个字符.字符串的尾随空字符正在&command + 1您的程序中写入.

你应该转到scanf:

commandcommand:

char command[2];
Run Code Online (Sandbox Code Playgroud)