无法找到内存泄漏的位置

unable to find where memory leaked

您好,我目前正在开发我的第一个面向对象的 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();

}

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

每个new应该有一个对应的delete。在您的 Game 构造函数中,您使用 new 创建 game_entity - 但析构函数不会删除它(只有它的 'members')。

在析构函数中 delete game_entity; for 循环之后需要一个 delete game_entity;