c - 使用 valgrind 修复内存泄漏

标签 c memory-management

我构建了一个链表库,并编写了一个清除函数,该函数遍历列表并释放与列表相关的所有内存。像这样:

/creating the list
list *myList = (list*) calloc(1, sizeof(list));

//lets try to add a node to the list
list_add_at (NULL, 0, (int*)100);
list_add_at (myList, 0, (int*)100);
list_add_at (myList, 1, (int*)200);
list_add_at (myList, 2, (int*)300);
list_add_at (myList, 3, (int*)400);
list_add_at (myList, 4, (int*)600);
list_add_at (myList, 5, (int*)800);

list_clear(myList);

然后当我运行 valgrind 时,它会说“间接丢失:5 个 block 中的 120 个字节”,这是我添加到列表中的节点数。 我的问题是如何释放我使用的这些内存位置?

谢谢

最佳答案

根据valgrind documentation ,

"indirectly lost" means your program is leaking memory in a pointer-based structure.

换句话说,这表明您的链表节点有另一个指针,您已将其设置为 malloc 的结果,并且您忘记了取消分配该内存。

修复方法是为链表节点内的指针添加 free:

while ( temp != NULL ){
        list->head = temp->next;
        free(temp->allocated_ptr); // <<= Free the memory attached to the node
        free(temp);
        temp = list->head;
}

关于c - 使用 valgrind 修复内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762559/

相关文章:

c++ - 我们可以免费使用多少内存(C++,Windows 7)

c - 在 C 中,指针值更改后内存值会发生什么情况?

memory-management - 在 OpenCL 内核中创建本地数组动态

c++ 对 c 函数 mbstowcs() 的调用更改参数

c++ - 生成唯一编号

c - 二维数组中的错误 scanf

在 C 中创建数组并将指向所述数组的指针传递给函数

c++ - 我如何计算bigmod(bigmod(a^n)-bigmod(b^m))?

linux - 如何在 Linux 中分配满足分页和缓存能力要求的内存?

c# - C#中如何实现malloc操作