我正在用C语言编写一个国际象棋引擎并通过Valgrind运行它并获得了这个:
==20217== 672 (32 direct, 640 indirect) bytes in 1 blocks are definitely lost in loss record 39 of 98
==20217== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==20217== by 0x40143A: register_move (Chess.c:236)
==20217== by 0x4015B6: scan_in_direction (Chess.c:256)
==20217== by 0x402131: getBishopMoves (Chess.c:374)
==20217== by 0x401296: getSquareMoves (Chess.c:190)
==20217== by 0x400C94: getAllMoves (Chess.c:60)
==20217== by 0x405C19: alphaBetaMax (MiniMax.c:260)
==20217== by 0x405D02: alphaBetaMax (MiniMax.c:274)
==20217== by 0x405D02: alphaBetaMax (MiniMax.c:274)
==20217== by 0x405D02: alphaBetaMax (MiniMax.c:274)
==20217== by 0x405ECD: getBestMove (MiniMax.c:307)
==20217== by 0x403933: computerTurn (Chess.c:850)
函数register_move
是:
static void register_move(game_t game, int x1, int y1, int x2, int y2, char special,
int color) {
move_t *tmpMove = (move_t *)malloc(sizeof(move_t));
checkMalloc(tmpMove);
tmpMove->x1 = x1;
tmpMove->y1 = y1;
tmpMove->x2 = x2;
tmpMove->y2 = y2;
tmpMove->s = special;
firstMove = addToList(game, firstMove, tmpMove, color); //firstMove is a global list of moves
}
编辑:为了进一步明确,move_t
定义为:
struct move_t {
int x1;
int y1;
int x2;
int y2;
char s;
struct move_t *next;
};
typedef struct move_t move_t;
更多编辑: firstMove是一个全局移动列表。上面引用的函数addToList是:
move_t *addToList(game_t game, move_t *list, move_t *move, int color) {
int kx, ky;
game_t copy;
copyGame(game, ©);
makeMove(©, *move);
kx = copy.data[2];
ky = copy.data[3];
if (color) {
kx = copy.data[0];
ky = copy.data[1];
}
if (isAttacked(©, kx, ky, color) == 0) {
move->next = list;
list = move;
} else {
free(move);
}
freeGame(copy);
return list;
}
如果潜在的举动是非法的,即curplayer的国王正在检查中,则移动不会被添加到列表中而是被释放。问题可能在于释放firstMove,这在整个程序中都会发生。
为什么Valgrind认为malloc似乎存在问题?对我来说似乎没问题。我怎么解释这个?