2
下面是一个简单的程序,它可以创建一个释放链接列表。但是,我不确定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被设置为NULL,那么它不是一个悬挂指针,或者是不必要的? –
@wm对于单链表,只有一种合理的释放方法 - 您编码的方法。人们也可以编码一个递归的,但这将是滥用递归。 – dasblinkenlight