[英]Memory leak when freeing linked list
我一直在学习C,并且有一段时间习惯了使用C进行内存管理。在学习了链表之后,我编写了该程序:
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
void free_node(struct node *n) {
struct node *p, *next;
for (p = n; p != NULL; p = next) {
next = p->next;
free(p);
}
}
int main(int argc, char const *argv[]) {
int i;
struct node *n, *p, *root = malloc(sizeof(struct node));
root->x = 0;
n = root;
for (i = 1; i <= 5; ++i) {
struct node *next = malloc(sizeof(struct node));
next->x = i;
n->next = next;
n = n->next;
}
n->next = NULL;
// print values
for (p = root; p != NULL; p = p->next) {
printf("%i\n", p->x);
}
free_node(n);
return 0;
}
我读过的大多数教程在解释C语言中的内存管理方面都做得很差,即使根本没有提到它。 我希望这段代码可以释放所有已分配的内存,但是当我运行它时: valgrind --track-origins=yes --leak-check=full ./linked_list
Valgrind告诉我这件事(我省略了消息的第一部分)确实没有包含信息):
0
1
2
3
4
5
==1366==
==1366== HEAP SUMMARY:
==1366== in use at exit: 29,618 bytes in 381 blocks
==1366== total heap usage: 460 allocs, 79 frees, 35,650 bytes allocated
==1366==
==1366== 80 (16 direct, 64 indirect) bytes in 1 blocks are definitely lost in loss record 46 of 78
==1366== at 0x6DFB: malloc (in /usr/local/Cellar/valgrind/3.9.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==1366== by 0x100000E87: main (in ./linked_list)
==1366==
==1366== LEAK SUMMARY:
==1366== definitely lost: 16 bytes in 1 blocks
==1366== indirectly lost: 64 bytes in 4 blocks
==1366== possibly lost: 0 bytes in 0 blocks
==1366== still reachable: 4,096 bytes in 1 blocks
==1366== suppressed: 25,442 bytes in 375 blocks
==1366== Reachable blocks (those to which a pointer was found) are not shown.
==1366== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==1366==
==1366== For counts of detected and suppressed errors, rerun with: -v
==1366== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 148 from 49)
我看了一下,找不到内存泄漏。 我很想知道为什么会这样,以及将来我可以做些什么来防止内存泄漏。 谢谢!
您正在释放n
,但这并不指向链接列表的开头...尝试将free_node
调用调整为:
free_node(root);
您应该尝试使用free_node(root)
因为调用free_node(n)
只会删除n
之后的节点(在这种情况下,仅删除最后一个节点),结果,之前的所有节点对于Valgrind都将丢失,因为它们不会被释放。
Valgrind还具有图形用户界面Valkyrie( http://valgrind.org/downloads/guis.html ),以可视化内存管理输出。
您可以使用选项valgrind选项“ --xml = yes --xml-file = .xml”生成xml文件,然后使用valkyrie显示xml文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.