用C++检测堆损坏

Bar*_*mey 0 c++ heap memory-management

我一直收到检测到Heap Corruption的错误.我在这里已经阅读了几个问题,但我无法在我的代码中找到导致这种情况的原因.我正在尝试创建一个2d数组,它将保存从文本文件中读取的矩阵.

// Create a 2d matrix to hold the matrix (i = rows, j = columns)
matrix = new int*[cols];

for(int i = 0; i <= cols; i++) {
    matrix[i] = new int[rows];
}

// Populate the matrix from the text file
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        inputFile >> matrix[i][j];
    }
}
Run Code Online (Sandbox Code Playgroud)

我的析构函数是:

for(int i = 0; i <= cols; i++) {
    delete[] matrix[i];
}

delete[] matrix;
Run Code Online (Sandbox Code Playgroud)

我已经尝试过调试,但在这种情况下确实提供了很多帮助.有什么建议?

Sum*_*Tea 5

matrix = new int*[cols];

for(int i = 0; i <= cols; i++) {
    matrix[i] = new int[rows];
}
Run Code Online (Sandbox Code Playgroud)

对于具有cols元素的数组,索引是从包含0cols - 1包含.

将在以下时检测到堆损坏

delete [] matrix;
Run Code Online (Sandbox Code Playgroud)

matrix[cols]写入数组绑定的位置.


UPDATE

正如@DanielKO(谢谢伙伴:p)在评论中指出的那样

存在不匹配,"填充矩阵......"循环使"i"迭代"行"时它应该迭代"cols".