在 C++ 语言中,我们可以用 new 语句动态申请堆空间给变量。变量使用完后最好使用 delete 语句去释放内存,不然会造成内存泄漏。可是我在写 3D 渲染时发现使用 new 申请动态二维数组触发了异常,请问是什么回事呢?
申请内存部分( PIXEL 是一个结构体,里面有两个成员变量 color 和 z):
void InitBuffer(int width, int height)
{
pixelbuffer = new PIXEL * [height]; // 帧缓存器
for (int i = 0; i < height; i++)
{
// 初始化
pixelbuffer[i] = new PIXEL[width];
for (int j = 0; j < width; j++)
{
pixelbuffer[i][j].color = -1;
pixelbuffer[i][j].z = 1e9;
}
}
}
释放内存部分:
void DeleteBuffer(int width, int height)
{
// 释放内存
for (int i = 0; i < height; i++)
{
delete pixelbuffer[i];
}
delete[] pixelbuffer;
}
运行程序时,触发了这样的异常提示:
Microsoft Visual C+ + Runtime Library
Debug Error!
Program: E:\...\Easy3D.exe
HEAP CORRUPTION DETECTED: after Normal block (#362811) at
0x000002BEF53ABCD0.
CRT detected that the application wrote to memory after end of heap
buffer.
(Press Retry to debug the application)
中止(A) 重试(R) 忽略(I)
请问是什么原因导致的异常呢?