分割故障(核心转储)误差小块代码

问题描述:

我有时会收到上面提到的错误,我知道它是由于下面的代码,但没有看到有什么能原因,作为即时通讯仍然很新的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]); 
+0

哪里定义了'maplength' /'mapheight',它们与'map'有什么关系? –

+1

除了'struct Point'(尽管我们可以猜到它的声明)请参阅:[**如何创建一个最小,完整和可验证的示例**](http://stackoverflow.com/help/mcve) “ –

+1

我在代码片段中看不到”map“被定义的任何地方,这肯定会导致段错误 –

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

使用valgrind和其他工具来获取更多信息,分段故障的原因是什么。