Hi I am currently working on my first object orientated c++ project, and when I use valgrind to check memory leakage it outputs:
32 (24 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==1761165== at 0x4839E86: operator new(unsigned long) (vg_replace_malloc.c:344)
==1761165== by 0x403E5C: Game::Game() (game.cpp:3)
==1761165== by 0x404711: Game::loadGame(std::istream&) (game.cpp:109)
==1761165== by 0x4024B2: main (main.cpp:29)
So now I go to game.cpp:3 to check what happened(in game.cpp:109, I called Game* temp_game=new Game), and in line 3 I called the constructor
Game::Game() : game_entity(new EntityVec) {
}
So I guess at some point, I didn't free EntityVec. But after double checking my code, especially loadGame function and my destructor:
Game *Game::loadGame(std::istream &in){
Game* temp_game=new Game;
temp_game->game_maze=Maze::read(in);
if (temp_game->game_maze == nullptr) {
delete temp_game;
return nullptr;
}
char c;int x;int y;
EntityControllerFactory* ecfac=EntityControllerFactory::getInstance();
while (in>>c){
Entity* temp_entity=new Entity;
temp_entity->setGlyph(std::string(1,c));
temp_game->addEntity(temp_entity);
if (in >> c) {
EntityController* temp_controller = ecfac->createFromChar(c);
temp_entity->setController(temp_controller);
}
else {
delete temp_game;
return nullptr;
}
if (in >> c) {
temp_entity->setProperties(std::string(1,c));
}
else {
delete temp_game;
return nullptr;
}
if((in>>x)&&(in>>y)){
temp_entity->setPosition(Position(x,y));
}
else {
delete temp_game;
return nullptr;
}
}
return temp_game;
}
Game::~Game(){
delete game_ui;
delete game_gameRules;
delete game_maze;
//delete[] game_entity;
for(Entity* p: *game_entity){delete p;}
//game_entity->clear();
}
I cannot find a spot where I forgot to free the game if loadgame fails.(If loadgame success and returned temp_game, then main should handled it by deleting it at the end). Can anyone give me some suggestions? Thank you so much.
Every new
should have a corresponding delete
. In your Game
constructor, you use new
to create game_entity
- but the destructor doesn't delete it (only its 'members').
You need a delete game_entity;
after the for
loop in the destructor.