c++ delete[] 二维数组导致堆损坏

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

当我尝试在 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,或智能指针。