为什么会泄漏内存?

rps*_*rps 2 c memory valgrind memory-leaks

我有一个函数,当被调用时,struct Pieces*从a 获取一个字段struct Torrent并根据char数组中包含的信息对其进行初始化.

这是函数调用的样子(metadata.c:230):

get_pieces(t.pieces, &t.num_pieces, data);
Run Code Online (Sandbox Code Playgroud)

get_pieces()函数中,我初始化t.pieces,就像这样(metadata.c:65):

pieces = calloc(*num_pieces, sizeof(struct Piece));
Run Code Online (Sandbox Code Playgroud)

但是,当我运行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)
Run Code Online (Sandbox Code Playgroud)

即使指针t->pieces仍在我的程序终止时仍可用,并且可以免费使用.为什么会泄漏内存?

完整的源代码可以在https://github.com/robertseaton/slug上找到.

cni*_*tar 8

你有

void get_pieces (struct Piece* pieces, uint64_t* num_pieces, char* data)
{
    /* ... */
    pieces = malloc(sizeof(struct Piece) * *num_pieces);
}
Run Code Online (Sandbox Code Playgroud)

函数完成后,调用者作为第一个参数传递的对象不变,因此结果malloc丢失.所以我看不出你如何自由pieces.

编辑

用户user786653在注释中观察,您需要更改您的功能:

void get_pieces(struct Piece **pieces...)
{
    /* ... */
    *pieces = malloc(sizeof(struct Piece) * num_pieces);
}
Run Code Online (Sandbox Code Playgroud)

  • +1我用相同的东西写了一个答案.OP应该将它改为`struct Piece**pieces`和`*pieces = malloc(....` (2认同)