【发布时间】:2013-07-06 12:05:13
【问题描述】:
我不断收到错误检测到堆损坏。我已经阅读了这里的几个问题,但我无法在我的代码中找出导致这种情况的原因。我正在尝试创建一个二维数组,该数组将保存从文本文件中读取的矩阵。
// 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];
}
}
我的析构函数是:
for(int i = 0; i <= cols; i++) {
delete[] matrix[i];
}
delete[] matrix;
我尝试过调试,但在这种情况下确实有很大帮助。有什么建议吗?
【问题讨论】:
-
您几乎不需要自己在 C++ 中管理内存。
new和delete应替换为 RAII。
标签: c++ memory-management heap-memory