分段错误(故障核心转储)
问题描述:
我有这个代码,它是一个函数,用于在二维数组中进行渗流模拟。分段错误(故障核心转储)
int step (double ** mat, unsigned n, unsigned m, double a, double b)
{
int i, h, r, c, steps, x, y, o, v; // search for minimum
int min;
FILE *fp;
for(steps=0; steps<2; steps++) // percolation steps
{
for (o=0; o<n; o++)
{
for(v=0; v<m; v++)
{
if (mat[o][v]==-2) {mat[o][v]=-1;}
}
} //trasformo i -2 in -1
min=b; //set the minimum to max of range
for(x=0; x<n; x++) // i search in the matrix the invaded boxes
{
for(y=0; y<m; y++)
{
if (mat[x][y]=-1) //control for the boxes
{
if (mat[x][y-1]<=min && mat[x][y-1]>=0) {min=mat[x][y-1]; r=x; c=y-1;} //look for the minimum adjacent left and right
if (mat[x][y+1]<=min && mat[x][y+1]>=0) {min=mat[x][y+1]; r=x; c=y+1;}
for (i=-1; i<=1; i++) //look for the minimum adjacent up and down
{
for(h=-1; h<=1; h++)
{
if (mat[(x)+i][(y)+h]<=min && mat[(x)+i][(y)+h]>=0)
{
min=mat[(x)+i][(y)+h];
r=(x)+i; c=(y)+h;
}
}
}
}
}
}
mat[r][c]=-2;
x=r; y=c;
}
return 0;
}
当我在main
函数中使用它,我获得Segmentation-fault (core dump created)
。你知道错误在哪里吗?
答
分段错误(SF)在您尝试访问未分配给程序的内存地址时生成。代码中存在一些错误
if (mat[x][y+1]<=min && mat[x][y+1]>=0)
这里,当y==m-1
时,索引将超出范围。这也适用于一些其它的数组索引环路
if (mat[x][y]=-1)
这里是打字错误内部,等于比较运算符应==
。
很难判断代码的哪一部分是为SF负责的。它将为您节省大量时间来使用调试器并在运行时捕获故障。然后您可以看到堆栈追溯并了解发生了什么。
答
分段错误是由您的程序尝试访问非法内存地址引起的。
我注意到,在功能,您有两个for循环,
for (i=-1; i<=1; i++) //look for the minimum adjacent up and down
{
for(h=-1; h<=1; h++)
{
if (mat[(x)+i][(y)+h]<=min && mat[(x)+i][(y)+h]>=0)
{
min=mat[(x)+i][(y)+h];
r=(x)+i; c=(y)+h;
}
}
}
“我” &“H”无论是从-1开始的变量,这将导致你访问垫[-1] [-1]开头,这不是程序访问的合法内存地址。
您应该重新设计您的循环以避免超出阵列的边界。
'mat [x] [y-1]''y = 0'会导致未定义的行为。 'y = m'和'mat [x] [y + 1]'相同。另外,使用'='而不是'=='。在编译器中启用警告。 – Zeta
那么,这是一个意大利面条... –
顺便说一句'if(mat [x] [y] = - 1)'? – BLUEPIXY