[英]access violation in deleting a 2d array
I have a 2d array of object pointers, and I am trying to write a deallocator for an object that to delete both the pointers in the array, and then delete the array itself. 我有对象指针的二维数组,我试图写一个释放器为对象的数组中删除这两个指针,然后删除该数组本身。 I define the array in the header of the object to be destructed like so
我限定在对象的头阵列被析构像这样
space* board[6][6];
I allocate the space objects in the array like so: 我分配像这样的阵列中的空间物体:
board[0][0]= new space(1,0);
board[0][1] = new space(1, 0);
board[0][2] = new space(1, 0);
My current destructor is like this 我目前的析构函数是这样的
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j){
delete board[i][j];
}
delete[] board[i];
}
delete[] board;
When I do this, I get this message: Unhandled exception at 0x5080A9E8 (msvcr120d.dll) in Blitz.exe: 0xC0000005: Access violation reading location 0xFEEEFEE2. 当我这样做,我得到这个消息:未处理的异常在0x5080A9E8(msvcr120d.dll)在Blitz.exe:0000005:访问冲突读取位置0xFEEEFEE2。
I'm not quite sure what to do, I've tried looking around, and it seems like my destructor should be okay. 我不太确定该怎么办,我尝试环顾四周,看来我的析构函数应该还可以。 I know if I had a decent programming education, I would use something better, like a vector or something else.
我知道,如果我有一个体面的编程教育,我会用更好的东西,就像一个载体或别的东西。 I downloaded a pdf on how people actually use C++ these days, and I'll probably go over that soon, but I would just rather just take care of this memory leak and move on.
我下载了有关人们近来如何实际使用C ++的pdf文件,我可能很快就会讲到,但是我只想处理这种内存泄漏并继续前进。
You are mixing new
with delete[]
. 您正在将
new
与delete[]
混合使用。 The behaviour of your program is therefore undefined . 因此,程序的行为是不确定的 。
It would be marginally better if you used std::vector<std::vector<space>>
instead. 如果您改用
std::vector<std::vector<space>>
会更好。 Then, the memory management would be done for you. 然后,将为您完成内存管理。
But if you're modelling a matrix then this is also not a good choice: it will have a "jagged edge" and the memory allocated is not contiguous. 但是,如果你正在制作一个矩阵那么这也不是一个好的选择:它会产生“锯齿状边缘”和分配的内存是不连续的。
A good alternative would be to allocate a contiguous block and use the convention (i * rows + j)
for the element at (i, j)
. 一个好的替代办法是分配一个连续块,并使用常规
(i * rows + j)
用于在元件(i, j)
A std::vector<space>
would suffice. 一个
std::vector<space>
就足够了。 Then consider using a 3rd party matrix library like BLAS (www.boost.org). 然后考虑使用第三方矩阵库,例如BLAS(www.boost.org)。
board
和board[i]
变量不应delete
d,因为它们尚未由new
分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.