【问题标题】:Segmentation Fault when using scanf with 3 input variables使用带有 3 个输入变量的 scanf 时出现分段错误
【发布时间】:2011-07-28 20:40:35
【问题描述】:

不知道为什么我在这里遇到分段错误:

//I define the variables used for input

int *numberOfDonuts;
    numberOfDonuts = (int *)malloc(sizeof(int));

char *charInput;
    charInput = (char *)malloc(sizeof(char));   

int *numberOfMilkshakes;
    numberOfMilkshakes = (int *)malloc(sizeof(int));

//Then attempt to read input
scanf("%c %d %d", &*charInput, &*numberOfDonuts, &*numberOfMilkshakes);

然后我在这条线上得到一个分段错误。无法弄清楚我做错了什么?

【问题讨论】:

  • 我没有看到这段代码有任何段错误。您可以尝试编译您的程序而不进行优化(例如 gcc -Wall -W -g program.c )吗?启用优化后,调试器可能不会将您带到发生段错误的确切行。
  • 既然你不检查来自malloc()的返回值,你有没有可能已经搞砸了内存分配系统并在这里访问空指针?
  • 如果删除所有出现的&* 会发生什么,即将其更改为scanf("%c %d %d", charInput, numberOfDonuts, numberOfMilkshakes);
  • 请不要从malloc(或callocrealloc)转换返回值,C语言中不需要,它可以隐藏问题。

标签: c malloc segmentation-fault scanf


【解决方案1】:

您分配变量的方式过于复杂。 这应该做你想做的事:

int numberOfDonuts;
char charInput;
int numberOfMilkshakes;

scanf("%c %d %d", &charInput, &numberOfDonuts, &numberOfMilkshakes);

对于intchar 等基本类型,您不必为它们显式分配内存。编译器会为您处理。

即使按照你的方式分配它们,你最终得到的是一个指向值的指针,而不是值本身。鉴于scanf 需要一堆指针,因此无需取消引用指针然后再次获取它的地址,这就是您想要做的。以下内容也将起作用:

int *numberOfDonuts;
    numberOfDonuts = malloc(sizeof(int));

char *charInput;
    charInput = malloc(sizeof(char));   

int *numberOfMilkshakes;
    numberOfMilkshakes = malloc(sizeof(int));

scanf("%c %d %d", charInput, numberOfDonuts, numberOfMilkshakes);

【讨论】:

  • @pmg:点了。自从我在 C 语言中做任何认真的工作以来已经有一段时间了。我基本上是试图展示组合的取消引用和地址操作符的冗余。我已经从我的答案中删除了演员表。
【解决方案2】:

据我所知,这段代码是有效的。

它在我的系统上编译并按预期工作。

这是你的全部程序吗?

您还应该注意,所有这些指针都不是必需的。

你可以这样写:

int numberOfDonuts;
char charInput;
int numberOfMilkshakes;

//Then attempt to read input
scanf("%c %d %d", &charInput, &numberOfDonuts, &numberOfMilkshakes);

printf("char=%c donuts=%d milkshakes=%d\n",
        charInput, numberOfDonuts, numberOfMilkshakes);

【讨论】:

  • 其实我不确定它是否严格有效,我的意思是意图很明确。
【解决方案3】:

当程序尝试访问无效的内存位置时会发生分段错误。

由于您在程序中使用 malloc 来分配内存,因此最好在尝试在该位置存储值之前检查是否返回了有效的内存位置。每次在您的程序中使用 malloc 来解决错误时都包括此检查。

例如:

int *numberOfDonuts = (int *)malloc(sizeof(int));
if(numberOfDonuts == NULL)
{
  printf("Memory allocation Failure\n");
  return;
}

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 2020-10-26
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2015-06-17
    • 2012-04-30
    • 1970-01-01
    相关资源
    最近更新 更多