0

调用树:populateMatrix(coeff,bMatrix, rows,cols); 求解矩阵(系数,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 周围的堆栈已损坏!!!

我一直在看这个,不明白为什么会这样。请帮忙。谢谢。

4

1 回答 1

1

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

最简单的调试方法如下:

  1. 彻底清除你的函数体。确保您不会再收到错误消息。
  2. 恢复第一个 for() 循环。看看这是否会导致错误出现。
  3. ...
  4. 重复它,直到找到函数的哪个确切部分导致错误。然后仔细查看并确保您没有超出数组限制(即,如果 bMatrix 是 float[16],则您没有编写 bMatrix[16]、[17] 或更多。
于 2012-07-10T15:40:37.767 回答