首页 > 解决方案 > 无法找到内存泄漏的位置

问题描述

嗨,我目前正在开发我的第一个面向对象的 c++ 项目,当我使用 valgrind 检查内存泄漏时,它会输出:

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)

所以现在我去game.cpp:3检查发生了什么(在game.cpp:109中,我调用了Game* temp_game=new Game),在第3行我调用了构造函数

Game::Game() : game_entity(new EntityVec) {
}

所以我想在某些时候,我没有释放 EntityVec。但是在仔细检查了我的代码之后,尤其是 loadGame 函数和我的析构函数:

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();

}

如果 loadgame 失败,我找不到忘记释放游戏的地方。(如果 loadgame 成功并返回 temp_game,那么 main 应该通过在最后删除它来处理它)。谁能给我一些建议?太感谢了。

标签: c++memory-leaksdestructordelete-operator

解决方案


每一个都new应该有对应的delete。在您的Game构造函数中,您用于new创建game_entity- 但析构函数不会删除它(仅删除它的“成员”)。

您需要在析构函数中的循环delete game_entity; 之后。for


推荐阅读