下面是一个简单的程序,可以创建一个链接列表 . 但是,我不确定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()
{
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;
};
1 回答
不,它不能 . 在C中没有任何构造允许动态分配的内存在通过调用
free()
显式释放后保持不变 .在函数结束时
tmp
确实指向最后一个节点的位置 . 但是,在这一点上它是一个悬垂的指针,所以它不会造成任何伤害 .你有什么是解放喜欢的列表的经典程序 . 这里要考虑的唯一修改是在循环体内声明
tmp
,因为它不在循环外使用: