【问题标题】:Heap Corruption Detected in C++在 C++ 中检测到堆损坏
【发布时间】: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++ 中管理内存。 newdelete 应替换为 RAII。

标签: c++ memory-management heap-memory


【解决方案1】:
matrix = new int*[cols];

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

对于具有cols 元素的数组,索引从0cols - 1(含)。

将检测到堆损坏

delete [] matrix;

由于matrix[cols] 写入了超出数组范围的位置。


更新

正如@DanielKO(谢谢你的朋友:p)在评论中指出的那样

不匹配,“填充矩阵...”循环使“i” 当它应该迭代“cols”时,迭代“rows”。

【讨论】:

  • 还有一个不匹配的地方,“填充矩阵...”循环使“i”在应该迭代“cols”时迭代“rows”。
  • @DanielKO 更新了答案。谢谢你:)
  • 谢谢你们!我知道这是一件很奇怪的事情。我只是无法完全发现它。
【解决方案2】:
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        inputFile >> matrix[i][j];

当您分配时,您从 i 中的 0 变为 cols。现在您将 i 更改为行。

编辑:以下将尊重您评论的行/列规则并遵循 RAII:

std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));

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

// no need for delete matrix cleaned up when leaving scope.

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多