Segmentation fault(故障core dump)

Segmentation fault (fault core dump)

我有这段代码,它是一个函数,用于在二维数组中进行渗透模拟。

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;
                        }    
                    }
                }

变量'i' & 'h'都是从-1开始的,这样会导致你访问到开头的mat[-1][-1],这不是合法的内存程序访问的地址。

您应该重新设计循环以避免超出数组的边界。