我有这段代码,它是一个函数,用于在二维数组中进行渗流模拟的步骤。
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)。你知道错误在哪里吗?
发布于 2016-05-13 13:35:19
当您试图访问未分配给程序的内存地址时,会生成分段错误(SF)。代码中有一些错误
if (mat[x][y+1]<=min && mat[x][y+1]>=0)在这里,当y==m-1时,索引将超出范围。这也适用于循环中的其他数组索引。
if (mat[x][y]=-1) 这里有一个输入错误,相等的比较操作符应该是==。
很难区分代码的哪一部分负责SF。使用调试器并在运行时捕获错误将节省大量时间。然后,您可以看到堆栈跟踪并了解发生了什么。
发布于 2016-05-13 14:40:45
分割错误是由程序试图访问的非法内存地址造成的。
我注意到函数中有两个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;
}
}
}变量'i‘和'h’都从-1开始,这将导致您在开始时访问mat -1,这不是程序要访问的合法内存地址。
您应该重新设计循环,以避免超出数组的边界。
https://stackoverflow.com/questions/37211258
复制相似问题