当我尝试在 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)
,元素编号是0
,…
,height - 1
.
改变两个for循环
for (int i = height; i >= 0; --i) {
到
for (int i = height - 1; i >= 0; --i) {
PS:在大多数情况下我们不需要手动使用原始指针和new
/delete
表达式,你可以只使用数组(不是原始的指针),或者 std::vector
和 std::array
,或者智能指针。
关于c++ delete[] 二维数组导致堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52214614/