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.
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.
You are mixing new
with delete[]
. The behaviour of your program is therefore undefined .
It would be marginally better if you used std::vector<std::vector<space>>
instead. 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)
. A std::vector<space>
would suffice. Then consider using a 3rd party matrix library like BLAS (www.boost.org).
board
和board[i]
变量不应delete
d,因为它们尚未由new
分配。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.