当我尝试在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
,或智能指针。