c - 为什么会泄漏内存?

标签 c memory memory-leaks valgrind

我有一个函数,当被调用时,它从 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/

相关文章:

android - 有没有办法在 Android 上可视化 Activity 堆栈(内存中的 Activity )?

memory-leaks - 非ARC项目:NSMutableArray,NSString内存泄漏

c - 在 C 中向文件写入结构体/从文件读取结构体

java - 强制 JVM 尽早收集垃圾并减少尽早使用的系统内存

matlab - 网格网格的内存高效替代品

linux - 就其第三个参数而言,mprotect() 作为 ASM 系统调用的用法是什么样的?

java - 可能的尝试/捕获和内存管理问题?

c - 具有共享内存和信号量的多个灵活阵列成员或 VLA

c - 在 C 中从双指针(指针到指针)分配 Int

c - fopen 用于读取/写入文件夹 C 中的多个文件