c - 释放链表时内存泄漏

标签 c memory-leaks linked-list valgrind free

我一直在学习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 语言的内存管理方面做得很糟糕,甚至根本没有提到它。我认为这段代码会释放所有 malloc 的内存,但是当我运行它时: valgrind --track-origins=yes --leak-check=full ./linked_list省略了没有真正包含信息的消息的第一部分):

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);

关于c - 释放链表时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986335/

相关文章:

java - 如何仅选择性地从 .txt 文件中读取数字和/或单词?

c++ - 链表函数cpp中的指针作用域

c - Linux 中的 ^X 是什么?

c - 关于字符串、空字符和strcmp

c - 新手 C 程序员如何检测内存泄漏

c# - 如果我将一个控件绑定(bind)到另一个控件,并且其中一个控件死亡,那么绑定(bind)会发生什么情况?

c - 修剪字符的末尾 *

c - C 中体系结构 x86_64 的 undefined symbol

android - 三星Note 3 : Activity Memory Leak after pressing SPen side button

java - 如何创建使用方法的链接列表数组