运行时检查失败#2 - bMatix周围的堆栈已损坏

时间:2012-07-10 14:23:17

标签: c++ gaussian

调用树: populateMatrix(coeff,bMatrix,rows,cols); solveMatrix(coeff,bMatrix,cols + 1);

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 个答案:

答案 0 :(得分:1)

问题发生的原因是你传递给solveMatrix()的实际矩阵大小(即cols + 1)大于实际数组的大小(coeff或bMatrix)。

最简单的调试方法如下:

  1. 彻底清除你的身体。确保您不会再收到错误消息。
  2. 恢复第一个for()循环。看看是否会导致出现错误。
  3. ...
  4. 重复此操作,直到找到函数的哪个确切部分导致错误。然后仔细查看它并确保你没有超过你的数组限制(即如果bMatrix是浮点数[16],你不是在写bMatrix [16],[17]或更多。