2014-09-29 58 views
0

我工作在C的國際象棋引擎運行Valgrind的時候,我發現了內存泄漏:無法理解Valgrind的的錯誤信息

==18455== 64 bytes in 1 blocks are definitely lost in loss record 9 of 199 
==18455== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==18455== by 0x40451C: copyGame (Chess.c:1093) 
==18455== by 0x401356: addToList (Chess.c:213) 
==18455== by 0x4014A0: register_move (Chess.c:245) 
==18455== by 0x4019C3: getPawnMoves (Chess.c:300) 
==18455== by 0x40119A: getSquareMoves (Chess.c:169) 
==18455== by 0x404F88: evaluate (MiniMax.c:69) 
==18455== by 0x405D93: alphaBetaMax (MiniMax.c:290) 
==18455== by 0x405CF6: alphaBetaMax (MiniMax.c:274) 
==18455== by 0x405CF6: alphaBetaMax (MiniMax.c:274) 
==18455== by 0x405EC1: getBestMove (MiniMax.c:307) 
==18455== by 0x403933: computerTurn (Chess.c:852) 

這裏發生的事情是這樣的:在電腦轉,後minimax算法達到深度0,它被稱爲評估。評估查看當前玩家的所有可能動作並將其添加到列表中。要檢查是否可以將移動添加到列表中,移動將在當前遊戲的副本上執行,並且程序會檢查當前玩家是否未被檢查(合法移動)。然後移動可以被添加。

由此我得到的似乎是與copyGame一個問題:

void copyGame(game_t game, game_t *copy) 
{ 
int i = 0, j = 0; 
copy->data = (int*)malloc(sizeof(int)* 16); 
checkMalloc(copy->data); 
copy->board = (board_t)malloc(sizeof(char*)*BOARD_SIZE); // board_t is char** 
checkMalloc(copy->board); 
for (i = 0; i<BOARD_SIZE; i++) 
{ 
    copy->board[i] = (char*)malloc(sizeof(char)*BOARD_SIZE); 
    checkMalloc(copy->board[i]); 
} 
for (i = 0; i<16; i++) 
{ 
    copy->data[i] = game.data[i]; //data contains additional information about the game 
} 
for (i = 0; i<BOARD_SIZE; i++) 
    for (j = 0; j<BOARD_SIZE; j++) 
    { 
     copy->board[i][j] = game.board[i][j]; 
    } 
} 

這裏是調用copyGame功能:

move_t* addToList(game_t game, move_t* list, move_t * move, int color) 
{ 
int kx, ky; 
game_t copy; 
copyGame(game, &copy); 
makeMove(&copy, *move); 

kx = copy.data[2]; 
ky = copy.data[3]; 
if (color) 
{ 
    kx = copy.data[0]; 
    ky = copy.data[1]; 
} 
if (isAttacked(&copy, kx, ky, color) == 0) // if curplayer's king isn't attacked 
{ 
    move->next = list; 
    list = move; 
} 
else 
{ 
    free(move); 
} 
freeGame(copy); 
return list; 
} 

但我懷疑問題可能與freeGame :

void freeGame(game_t game) 
{ 
int i = 0; 
for (i = 0; i<BOARD_SIZE; i++) 
{ 
    free(game.board[i]); 
} 
free(game.data); 
} 

我只是不明白Valgrind提出的錯誤,而wo如果有更多C經驗的人可以幫忙,我很感激。謝謝閱讀。

+0

Valgrind說有問題的錯誤在'Chess.c'的第1093行。 'copyGame'中的哪個'malloc'在該行? – jlahd 2014-09-29 11:32:52

+0

另外一個問題可能會更好(因爲這兩個問題並不相關)。但後續問題的主要問題是,您根本沒有粘貼實際的錯誤消息,只有位置和堆棧跟蹤... – jlahd 2014-09-29 12:34:45

回答

1

您正在釋放game.data以及每個game.board[i]。但是你不能釋放game.board本身(copyGame中的第二個malloc)。將此添加到freeGame的末尾:

free(game.board); 
+0

感謝您的支持,它已經修復!有沒有辦法就類似的問題提出後續問題? – John 2014-09-29 11:44:08

+0

不出所料,有[Q + A關於此](http://meta.stackexchange.com/questions/10243/asking-a-follow-up-question):) – jlahd 2014-09-29 11:46:35

+0

謝謝!我添加了一個後續。 – John 2014-09-29 11:57:51