c++ - 无法找到内存泄漏的位置
问题描述
嗨,我目前正在开发我的第一个面向对象的 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 应该通过在最后删除它来处理它)。谁能给我一些建议?太感谢了。
解决方案
每一个都new
应该有对应的delete
。在您的Game
构造函数中,您用于new
创建game_entity
- 但析构函数不会删除它(仅删除它的“成员”)。
您需要在析构函数中的循环delete game_entity;
之后。for
推荐阅读
- powershell - 如果 .txt 文件中存在匹配,则修复将文件移动到年份文件夹
- android - 自定义警报对话框搜索项目结果错误
- c# - 返回的 SqlDataAdapter 计数行
- armflang - 使用 armflang 在 -Ofast 级别编译时的 Fortran 程序段错误
- firebase - Firebase 和 AngularDart。错误:准备要上传的托管文件时出现问题
- php - 通过使用 PHP 选择复选框来选择和删除多行
- javascript - 使用 Ajax 查看的 jQuery POST 表单
- c - C for 循环与推出循环的效果不同
- django - 检查一系列值
- active-directory - 用户无法创建 Azure AD 应用程序