删除矩阵时的访问冲突写入位置

Access violation writing location when deleting a matrix

本文关键字:位置 访问冲突 删除      更新时间:2023-10-16

我正在写一个程序来执行一组数值方法。要做到这一点,我需要创建任意大小的矩阵,并将它们放在函数之间。显然,如果我在使用create矩阵后不清理它们,我就会得到相当严重的内存泄漏。

double** MatrixInitialize(int m, int n)//generates a A[m][n] matrix
{
    int i = 0, j = 0;
    double** B = new double*[m];
    for (m = 0; m < n; m++)
    {
            B[m] = new double[n];
    }
    for (j = 0;j<m;j++)
            for (i = 0; i < n; i++)
            {
                    B[i][j] = 0;
            }
    return(B);
}
int main()
{
    double** MatrixA;
    MatrixA=MatrixInitialize(2,2) 
    //Some manipulation on MatrixA is done here
    delete[] MatrixA[0]; delete[] MatrixA[1]; delete[] MatrixA; 
    return 0;
}

一旦调用delete[]行,就会抛出访问冲突消息,必须中断。删除这些指针还有其他的步骤吗?

让语言为你工作

int main()
{
    int ysize = 10;
    int xsize = 5;
    std::vector<std::vector<double>> B(ysize, std::vector<double>(xsize, 0));
    for (int y = 0; y < ysize; y++)
    {
        for (int x = 0; x < xsize; x++)
        {
            B[y][x] = 1.23;
        }
    }
    for (int y = 0; y < ysize; y++)
    {
        for (int x = 0; x < xsize; x++)
        {
            std::cout << B[y][x] << " ";
        }
    }
    std::cout << "n";
}
http://ideone.com/QSoR5M