简体   繁体   English

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

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

When I tried to delete a 2-D array in C++ , it caused an error in Visual Studio 2017: 当我尝试删除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.

The code is below: 代码如下:

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

What's wrong with the code please? 请问代码有什么问题?

You're getting out of the bound of the array; 您将超出数组的范围; which leads to UB. 导致UB。 Note that the range is [0, height) , the elements are numbered 0 , , height - 1 . 请注意,范围为[0, height) ,元素编号为0height - 1

Change the two for loop from 从更改两个for循环

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

to

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

PS: In most cases we don't need to use raw pointers and new / delete expression manually, you can just use array (not with raw pointer), or std::vector and std::array , or smart pointers instead. PS:在大多数情况下,我们不需要手动使用原始指针和new / delete表达式,您可以使用数组(不使用原始指针)或std::vectorstd::array或智能指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM