c - 确保链接列表已释放

标签 c list memory-management linked-list

下面是一个创建释放链接列表的简单程序。但是,我不确定 free_list 函数是否确保释放所有分配的内存。

这是主函数,它只调用其他两个函数:

int main(int argc, char *argv[])
{
    struct node *head = build_list();
    free_list(head);

    return 0;
}

build_list() 创建一个简单的三成员列表:

struct node *build_list()
{
    struct node *head = malloc(sizeof(struct node));
    struct node *two = malloc(sizeof(struct node));
    struct node *three = malloc(sizeof(struct node));

    head->data = 0;
    head->next = two;

    two->data = 1;
    two->next = three;

    three->data = 2;
    three->next = NULL;

    return head;
}

并且 free_list() 尝试按顺序释放列表中的每个成员:

void free_list(struct node *curr)
{
    struct node *tmp;

    while (curr) {
        tmp = curr;
        curr = tmp->next;
        free(tmp);
    }
}

我的问题是这是否会释放所有分配的内存。看起来似乎应该如此,但我不确定使用 *tmp 是否会导致内存块保持分配状态。最后,任何有关释放链接列表的最佳实践的建议将不胜感激。

谢谢!

作为引用,这里是节点结构:

struct node {
    int data;
    struct node *next;
};

最佳答案

I am unsure whether or not the use *tmp could cause a block of memory to remain allocated.

不,不能。 C 中没有任何结构允许动态分配的内存在通过调用 free() 显式释放后保留。

在函数的末尾tmp确实指向最后一个节点的位置。然而,此时它是一个悬空指针,因此不会造成任何损害。

any advice on the best practices for freeing a linked list would be much appreciated.

您拥有的是用于释放喜欢列表的经典程序。 这里要考虑的唯一修改是在循环体内声明 tmp 它,因为它不在循环外部使用:

while (curr) {
    struct node * tmp = curr;
    curr = tmp->next;
    free(tmp);
}

关于c - 确保链接列表已释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378787/

相关文章:

c++ - 使用 rtsp、visual studio OpenCv 2.4.5 访问 IP 摄像机?

c - 为什么我在这里得到一个SIGABRT?

list - 在 Haskell 中创建一个数字递增的列表列表

java - 使用 final 关键字声明一个列表字段

python - 如何确保列表包含唯一元素?

cocoa-touch - 使用dismissModalViewControllerAnimated 不会释放任何内存

C: ncurses, initscr() 改变了 getchar() 的行为?

r - 意外的 R 内存管理行为

mysql - 数据库内存和磁盘工作分配

无法将节点附加到 C 中链表的末尾