c++ delete[] 二维数组导致堆损坏

标签 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

请问代码有什么问题?

最佳答案

你正在离开数组的边界;这导致了 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,或者智能指针。

关于c++ delete[] 二维数组导致堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52214614/

相关文章:

JavaScript 按值复制数组

c++ - Boost find_first 它是如何工作的?/定义一个范围

c++ - 调用函数

c++ - 如何为函数中的 vector 参数指定默认值

c++ - 定义一个非常大的数组(查找表)的最佳方法是什么?

python - 如何绘制二维直方图?

java - repaint() 不再工作

python - 检查二维列表中的对角线(Python)

c++ - 如何开发新的Qt GUI控件?

c++ - WTL 和 CContainedWindow 导致访问冲突