C++ 删除[] 2D 数组导致堆损坏
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)
,元素编号为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++ 动态 2D 数组之后
- 损坏的结构字符数组 - sqlite C++
- C++ 删除[] 2D 数组导致堆损坏
- 类数组正在损坏数据
- 调用delete[]时,某些东西导致堆损坏,但我已正确设置了数组的维度
- 数组变量周围的堆栈已损坏
- Arduino 数组中的值损坏
- malloc()内存损坏仅通过为特定数量编写int数组
- 填充另一个 2D 数组后,堆已损坏
- 在复制 delete[] 数组后在 C++ 中检测到堆损坏
- 数组问题:变量周围的堆栈'arr'已损坏
- 访问边界外的数组元素会损坏它
- 重叠的多维数组损坏
- C++ 删除数组时检测到堆损坏
- 动态数组的双重释放或损坏
- 将数据存储在char数组中导致变量周围损坏
- C++指针:数组的堆栈已损坏
- 我找不到导致我的数组在运行两次案例并退出后损坏的错误
- 字符指针指向字符串,然后指向字符串数组。"./a.out"中的错误:malloc():内存损坏:0x0900c3b0***
- 删除全局数组时堆损坏