2016-05-13 108 views
0

我有這個代碼,它是一個函數,用於在二維數組中進行滲流模擬。分段錯誤(故障核心轉儲)

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)。你知道錯誤在哪裏嗎?

+4

'mat [x] [y-1]''y = 0'會導致未定義的行爲。 'y = m'和'mat [x] [y + 1]'相同。另外,使用'='而不是'=='。在編譯器中啓用警告。 – Zeta

+4

那麼,這是一個意大利麪條... –

+0

順便說一句'if(mat [x] [y] = - 1)'? – BLUEPIXY

回答

0

分段錯誤(SF)在您嘗試訪問未分配給程序的內存地址時生成。代碼中存在一些錯誤

if (mat[x][y+1]<=min && mat[x][y+1]>=0) 

這裏,當y==m-1時,索引將超出範圍。這也適用於一些其它的數組索引環路

if (mat[x][y]=-1) 

這裏是打字錯誤內部,等於比較運算符應==

很難判斷代碼的哪一部分是爲SF負責的。它將爲您節省大量時間來使用調試器並在運行時捕獲故障。然後您可以看到堆棧追溯並瞭解發生了什麼。

0

分段錯誤是由您的程序嘗試訪問非法內存地址引起的。

我注意到,在功能,您有兩個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]開頭,這不是程序訪問的合法內存地址。

您應該重新設計您的循環以避免超出陣列的邊界。