c ++ delete [] 2d数组导致堆损坏

时间:2018-09-07 02:52:59

标签: c++ arrays 2d free

当我尝试删除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

请问代码有什么问题?

1 个答案:

答案 0 :(得分:1)

您将超出数组的范围;导致UB。请注意,范围为[0, height),元素编号为0height - 1

从更改两个for循环

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

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

PS:在大多数情况下,我们不需要手动使用原始指针和new / delete表达式,您可以只使用数组(不适用于原始指针)或{{ 1}}和std::vector,或者使用智能指针。