c-确保链接列表已释放



下面是一个创建frees链表的简单程序。但是,我不确定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;
};

我不确定使用*tmp是否会导致内存块保持分配状态。

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

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

任何关于释放链接列表的最佳实践的建议都将不胜感激。

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

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

最新更新