我有一个函数,当被调用时,它从 struct Torrent
中获取一个 struct Pieces*
字段,并根据 char 数组中包含的信息对其进行初始化。
这是函数调用的样子 (metadata.c:230):
get_pieces(t.pieces, &t.num_pieces, data);
在 get_pieces()
函数中,我初始化了 t.pieces
,就像这样 (metadata.c:65):
pieces = calloc(*num_pieces, sizeof(struct Piece));
但是,当我运行 valgrind 时,它显示:
==8701== 76,776 bytes in 1 blocks are definitely lost in loss record 634 of 634
==8701== at 0x4C28349: calloc (vg_replace_malloc.c:467)
==8701== by 0x4025A4: get_pieces (metadata.c:65)
==8701== by 0x402CDB: init_torrent (metadata.c:230)
==8701== by 0x404018: start_torrent (torrent.c:35)
==8701== by 0x40232E: main (main.c:17)
即使指针 t->pieces
在我的程序终止时仍然可用并且可以被释放。为什么会泄漏内存?
完整的源代码可在 https://github.com/robertseaton/slug 获得。 .
最佳答案
你有
void get_pieces (struct Piece* pieces, uint64_t* num_pieces, char* data)
{
/* ... */
pieces = malloc(sizeof(struct Piece) * *num_pieces);
}
函数完成后,调用者作为第一个参数传递的对象没有改变,所以malloc
的结果丢失了。因此,我看不出如何释放 pieces
。
编辑
正如用户 user786653 在评论中所说,您需要更改您的功能:
void get_pieces(struct Piece **pieces...)
{
/* ... */
*pieces = malloc(sizeof(struct Piece) * num_pieces);
}
关于c - 为什么会泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7029237/