简体   繁体   English

GCC`scanf`分段故障

[英]GCC `scanf` segmentation fault

I was playing around with C and the scanf function and came across this weird error that I can't seem to figure out. 我正在玩C和scanf函数,并遇到了这个奇怪的错误,我似乎无法弄清楚。 Given the following code: 给出以下代码:

#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;
}

It seems to seg fault. 这似乎是错误的。 With the output: 随着输出:

$ ./sample
Before sample function: 4
a
Read: a
In the sample function:, 4
Segmentation fault (core dumped)

I used gdb and attached a watch to the struct, it seems that inside the scanf function, it seems to 'modify' the struct? 我用了gdb并在结构上附加了一个watch ,看来在scanf函数里面,它似乎“修改”了结构体? Which is weird, because even after the scanf inside the sample function ' fn ', it is able to print out the struct fields fine. 这很奇怪,因为即使在示例函数' fn '中的scanf之后,它也能够很好地打印出struct字段。 However, once returning from the fn and jumping back into main , it seg faults when it tries to print out the same information? 但是,一旦从fn返回并跳回main ,它会在尝试打印出相同的信息时出现故障?

Interestingly, if you change the scanf to scanf("%c\\n", &command); 有趣的是,如果将scanf更改为scanf("%c\\n", &command); (without the character set) it seems to work fine. (没有字符集)它似乎工作正常。 For the record, the version of gcc I am using is 4.7.2, and I am compiling the code with: gcc -O0 -o sample sample.c . 为了记录,我使用的gcc版本是4.7.2,我用以下代码编译代码: gcc -O0 -o sample sample.c

My only thought is that perhaps character sets aren't supported by gcc? 我唯一想到的是gcc可能不支持字符集吗? I'm not sure. 我不确定。 Just wondering if anyone else could clear this up? 只是想知道是否有其他人可以解决这个问题?

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

writes a string not a single character. 写一个字符串而不是一个字符。 The trailing null character of the string is being written in &command + 1 in your program. 字符串的尾随空字符正在程序中的&command + 1中写入。

You should pass to scanf something like: 你应该传递给scanf

command with command being: commandcommand

char command[2];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM