C++ 删除[] 2D 数组导致堆损坏

c++ delete[] 2d array caused Heap Corruption

本文关键字:损坏 数组 2D 删除 C++      更新时间:2023-10-16

当我尝试删除C++中的二维数组时,它在Visual Studio 2017中导致错误:

HEAP CORRUPTION DETECTED: after Normal block (#530965) at 0x0ACDF348.
CRT detected that the application wrote to memory after end of heap buffer.

代码如下:

const int width = 5;
const int height = 5;
bool** map = new bool*[height];
for (int i = height; i >= 0; --i) {
map[i] = new bool[width];
}
for (int i = height; i >= 0; --i) {
delete[] map[i];
}
delete[] map; // error occurs here

请问代码有什么问题?

你正在脱离数组的范围;这会导致 UB。注意范围是[0, height),元素编号为0height - 1

将两个 for 循环从

for (int i = height; i >= 0; --i) {

for (int i = height - 1; i >= 0; --i) {

PS:在大多数情况下,我们不需要手动使用原始指针和new/delete表达式,您只需使用数组(不使用原始指针(,或std::vectorstd::array,或智能指针代替。