gpt4 book ai didi

c - Valgrind 说 "definitely leak"但它是吗?

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:58 25 4
gpt4 key购买 nike

我正在尝试为井字游戏编写蒙特卡洛树搜索,但在运行时确实存在内存问题(例如,我的计算机内存不足)。

所以我决定用 valgrind 调查情况。

下面是 valgrind 说“绝对泄漏”的代码块之一。

void player_init (Player **p, player_t symbol)
{
*p = (Player *) malloc (sizeof (Player));
(**p).symbol = symbol;
(**p).score = 0;
}

void player_init_all (Player ***p)
{
*p = (Player **) malloc (sizeof (Player *) * 2);
for (int i = 0; i < 2; i++)
{
(*p)[i] = (Player *) malloc (sizeof (Player));
}
player_init (&(*p)[0], PLAYER1);
player_init (&(*p)[1], PLAYER2);
}

void player_destroy (Player *p)
{
free (p);
}

其中 Playerplayer_t

typedef char player_t;
typedef struct player Player;
struct player {
player_t symbol;
unsigned score;
};

他们就是这样使用的;

int main (int argc, char** argv)
{
Player **players;
player_init_all (&players);

// OTHER FANCY CODE HERE

for (int i = 0; i < 2; i++)
player_destroy (players[i]);

free (players);
free (board);
return 0;
}

我是否以错误的方式传递指针?

Valgrind 转储;

==21657== 16 bytes in 1 blocks are definitely lost in loss record 1 of 15
==21657== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21657== by 0x40147D: player_init_all (main.c:348)
==21657== by 0x401698: main (main.c:426)
==21657==
==21657== 16 bytes in 2 blocks are definitely lost in loss record 2 of 15
==21657== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21657== by 0x4014AF: player_init_all (main.c:351)
==21657== by 0x401698: main (main.c:426)

第 348 行player_init_all 的开始,第 351 行for 循环的开始>player_init_all

最佳答案

这里有一个相当明显的内存泄漏

void player_init_all (Player ***p)
{
*p = (Player **) malloc (sizeof (Player *) * 2);
for (int i = 0; i < 2; i++)
{
(*p)[i] = (Player *) malloc (sizeof (Player));
}
player_init (&(*p)[0], PLAYER1);
player_init (&(*p)[1], PLAYER2);
}

您在上述循环中为 Player 对象分配内存。但紧接着 player_init 将再次分配它并覆盖 (*p)[0](*p)[1] 的值,肯定会泄漏您在上述循环中分配的内容。

关于c - Valgrind 说 "definitely leak"但它是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47763135/

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