gpt4 book ai didi

c++ - 为什么我在这里泄漏内存(深度优先搜索)C++?

转载 作者:行者123 更新时间:2023-11-28 00:59:18 24 4
gpt4 key购买 nike

int Solver::negamax(Position* pos,int alpha,int beta, int color, int depth ) {
if(depth==0 || is_final(pos)){
return evaluate(pos);
}
else{
vector < Position* > moves = generate_moves(pos->get_board());
vector < Position* >::iterator move;
int min = 99999;
for(move = moves.begin(); move < moves.end(); move++){
int val = negamax(*move,alpha, beta, -color, depth - 1 );
if(val <= min){
min = val;
delete best;
best = NULL;
best = (*move)->get_board();

}
else{
delete *move; //So this isnt cleaning up?
*move = NULL;
}
}
min = -min;
return min;
}

}

vector < Position* > TakeAwaySolver::generate_moves(Board *brd){
TakeAwayBoard *board = static_cast<TakeAwayBoard*>(brd);
vector < Position* > moves;
if(board->get_data() >= 3){
TakeAwayBoard *b = new TakeAwayBoard(board->get_data() - 3);
Position* p = new Position(b);
moves.push_back(p);
}
if(board->get_data() >= 2){
TakeAwayBoard *b = new TakeAwayBoard(board->get_data() - 2);
Position* p = new Position(b);
moves.push_back(p);
}
TakeAwayBoard *b = new TakeAwayBoard(board->get_data() - 1);
Position* p = new Position(b);
moves.push_back(p);
return moves;

我对我的程序进行了 valgrinded,显然我正在泄漏内存。似乎我正在删除所有未使用的对象,但也许我不理解某些东西。 generate_moves() 确实为每个被插入的对象分配内存。评估返回 1。我是否有可能在任何位置泄漏内存?

最佳答案

您有一个 if/else,其中 *move 仅在其中一个路径中被删除。我会在那里检查。

for(move = moves.begin(); move < moves.end(); move++){
int val = negamax(*move,alpha, beta, -color, depth - 1 );
if(val <= min){
min = val;
delete best;
best = NULL;
best = (*move)->get_board();
//best is deleted, but *move is not
}
else{
delete *move;
*move = NULL;
}
}

关于c++ - 为什么我在这里泄漏内存(深度优先搜索)C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9624189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com