C 确保链接列表被释放
下面是一个简单的程序,它创建了一个“释放”链接列表。但是,我不确定free_list函数是否确保释放所有分配的内存 这里是main函数,它只调用其他两个函数:C 确保链接列表被释放,c,list,memory-management,linked-list,C,List,Memory Management,Linked List,下面是一个简单的程序,它创建了一个“释放”链接列表。但是,我不确定free_list函数是否确保释放所有分配的内存 这里是main函数,它只调用其他两个函数: int main(int argc, char *argv[]) { struct node *head = build_list(); free_list(head); return 0; } build_list()创建一个简单的三人列表: struct node *build_list() { s
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);
}
释放列表时首选哪种方法(如果有)?另外,tmp是否应该设置为NULL,这样它就不是一个悬空的指针,或者这是不必要的?@wm对于单链表,只有一种合理的释放方法——您编写的方法。也可以编写递归代码,但这将是对递归的滥用。