c ++ delete [] 2d数组导致堆腐败

问题描述 投票:0回答:1

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

请问代码有什么问题?

c++ arrays 2d free
1个回答
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表达式,您可以使用数组(不使用原始指针),或std::vectorstd::array,或智能指针。

© www.soinside.com 2019 - 2024. All rights reserved.