2012-07-10 138 views
0

調用樹: populateMatrix(_係數,bMatrix,行的cols); solveMatrix(coeff,bMatrix,cols + 1);運行時檢查失敗#2 - 圍繞bMatix堆棧被損壞

void solveMatrix(float aMatrix[][DEFCOLS+1],float bMatrix[DEFCOLS+1], size_t cols){ 
std::cout << "\nInside solveMatrix...: " << endl; 
size_t N2 = cols; 

std::cout << "\N2 is...: " << N2 << endl; 
for(size_t p=0; p<N2; p++){ 
    //std::cout << "\nInside 1st for loop...: " << endl; 
    // find pivot row and swap 
    int max = p; 
    for(size_t i=p+1; i<N2; i++){ 
     //std::cout << "\nInside 2nd for loop...: " << endl; 
     if (abs(aMatrix[i][p]) > abs(aMatrix[max][p])){ 
      max = i; 
     } 
    } 

    //std::cout << "\nJust b4 all the swapping...: " << endl; 

    float temp[] = { *aMatrix[p] }; 
    *aMatrix[p] = *aMatrix[max]; 

    *aMatrix[max] = *temp; 

    float t = bMatrix[p]; 
    bMatrix[p] = bMatrix[max]; 


    bMatrix[max] = t; 
    //std::cout << "\nDone all the swapping...: " << endl; 

    if (abs(aMatrix[p][p]) <= MINISCULE) { 
     std::cout << "***** Error matrix value too small. Matrix is singular" << endl; 
     return; 
    } 
    // Pivot /in A and b 
    for(size_t i=p+1; i<N2; i++){ 
     float alpha = aMatrix[i][p]/aMatrix[p][p]; 

     bMatrix[i] = alpha * bMatrix[p]; 

     for(size_t j=p; j<N2; j++){ 
      aMatrix[i][j] -= alpha * aMatrix[p][j]; 
     } 

    } 

    std::cout << "\nAbout to do the back subst..: " << endl; 
    // back subst. 
    std::vector<float> outMatrix(N2, 0.0); 
    int i =0; 

    for(i=N2-1; i>=0; i--){ 
     float sum = 0.0; 
     int j=0; 
     for(j=i+1; j<N2; j++){ 
      sum += aMatrix[i][j] * outMatrix[j]; 
     }  
     if (aMatrix[i][i] > 0){ 
      outMatrix[i] = (bMatrix[i] - sum)/aMatrix[i][i]; 
     }else { 
      outMatrix[i] = 0.0; 
     } 
    } 

    int g = 0; 
    std::cout << "\nSolution: " << endl; 
    for (;g < N2-1; g++) { 
     cout << outMatrix[g] << " "; 
    } 
    cout << endl; 
    return; 
} 

} //結束solveMatrix()

這高斯消去具有部分樞轉的實施方式。應用程序 運行並給出結果 - 不正確的重試,但在返回後,我得到下面的錯誤。

只要它返回到通話頂部,我就會得到: 運行時檢查失敗#2 - bMatrix周圍的堆棧已損壞!

我已經看過這個永遠不能明白爲什麼是這種情況。 請幫忙。謝謝。

回答

1

問題發生是因爲您傳遞給solveMatrix()(即cols + 1)的實際矩陣大小大於實際數組的大小(coeff或bMatrix)。

調試最簡單的方法是:你的函數

  1. 徹底清除體內。確保您不會再收到錯誤消息。
  2. 恢復()循環的第一個。看看是否會導致錯誤出現。
  3. ...
  4. 重複,直到你找到它的功能的確切部分導致錯誤。再仔細查看一下,確保您不超過你的數組的限制條件(即,如果bMatrix爲float [16],你不寫bMatrix [16],[17]以上。
相關問題