So, I have a class
class Room {
public:
Room();
~Room();
tile::Tile* tile[11][7]; // Owned
}
The has a constructor and destructor, tile::Tile
is an abstract base class, so is a pointer. The array of pointers tile, need to be populated in the constructor like this.
Room::Room() {
for (std::size_t i = 0; i < 11; ++i) {
for (std::size_t j = 0; j < 7; ++j) {
this->tile[i][j] = new tile::Empty();
}
}
}
From my understanding, I should also delete these in Room
's destructor.
Room::~Room() {
for (std::size_t i = 0; i < 11; ++i) {
for (std::size_t j = 0; j < 7; ++j) {
delete this->tile[i][j];
}
}
}
However, doing this results in a return code of 0xc0000374
, which is a heap corruption error. Why is this corruption error happening?
Minimum example
class Tile {};
class Empty: public Tile {
public:
Empty() {}
};
class Room {
public:
Tile* tiles[5];
Room() {
for (int i = 0; i < 5; ++i) {
tiles[i] = new Empty();
}
}
~Room() {
for (int i = 0; i < 5; ++i) {
delete tiles[i];
}
}
};
class Maze {
public:
Room rooms[5];
Maze() {
for (int i = 0; i < 5; ++i) {
rooms[i] = Room();
}
}
};
int main() {
Maze maze = Maze();
}
If this is all the code then it looks ok. I assume you have some more code that deletes some of these entries before the destructor.
In any case you must assign a NULL
to pointers right after deletion so additional calls to delete
will not raise exception.
If there is other code that did call delete
before the destructor and did not assign a NULL
to the pointer(s) then this will explain the exception.
Alright, so the problem for my code was actually in the construction of the Room object. I had a loop intializing a 5 by 5 array with the default constructor (i.e. rooms[i][j] = Room()
). Removing this (as C++ will automatically use the default constructor for arrays) solved the problem!
class Tile {};
class Empty: public Tile {
public:
Empty() {}
};
class Room {
public:
Tile* tiles[5];
Room() {
for (int i = 0; i < 5; ++i) {
tiles[i] = new Empty();
}
}
~Room() {
for (int i = 0; i < 5; ++i) {
delete tiles[i];
}
}
};
class Maze {
public:
Room rooms[5];
Maze() {
//for (int i = 0; i < 5; ++i) {
// rooms[i] = Room();
//}
}
};
int main() {
Maze maze = Maze();
}
User contributions licensed under CC BY-SA 3.0