【问题标题】:Segmentation fault (core dumped) error with small piece of code带有一小段代码的分段错误(核心转储)错误
【发布时间】:2016-04-25 18:43:59
【问题描述】:

我有时会遇到上述错误,我知道这是由于以下代码造成的,但不知道可能是什么原因,因为我对 C 语言还是很陌生。

struct Point playerPosition;
int counter = 0;
do {
    playerPosition.x = rand() % mapLength;
    playerPosition.y = rand() % mapHeight;
    counter++;
    printf("The current tile that is being tried is: %c\n", map[playerPosition.x][playerPosition.y]);
} while((counter < (mapLength*mapHeight)) && ((map[playerPosition.x][playerPosition.y] == '#') || (map[playerPosition.x][playerPosition.y] == 'P')));
printf("A tile was found at %d %d, with the tile being %c\n", playerPosition.x, playerPosition.y, map[playerPosition.x][playerPosition.y]);

【问题讨论】:

  • maplength/mapheight 定义在哪里,它们与map 有什么关系?
  • 还有struct Point(虽然我们可以猜到它的声明)参见:How to create a Minimal, Complete, and Verifiable example。”
  • 我在您的代码 sn-p 中没有看到定义 map 的任何地方。这肯定会导致段错误。
  • 数据类型/声明至少和代码一样重要。你应该包括他们。

标签: c struct segmentation-fault


【解决方案1】:

您的示例代码中缺少某些部分,但问题很可能在于访问maprand() 的定义也很重要。如果它提供介于 -1 和 1 之间的值,则最终会出现分段错误。

使用valgrind等工具获取更多信息,分段错误的原因是什么。

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2012-11-19
    • 1970-01-01
    • 2015-06-25
    相关资源
    最近更新 更多