如何释放在另一个函数中分配的节点?
struct node {
int data;
struct node* next;
};
struct node* buildList()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
return head;
}
我调用main()中的buildList函数
int main()
{
struct node* h = buildList();
printf("The second element is %dn", h->next->data);
return 0;
}
我想要释放头,第二和第三个变量
谢谢
更新:
int main()
{
struct node* h = buildList();
printf("The element is %dn", h->next->data); //prints 2
//free(h->next->next);
//free(h->next);
free(h);
// struct node* h1 = buildList();
printf("The element is %dn", h->next->data); //print 2 ?? why?
return 0;
}
两张照片都是2。不应该调用free(h)remove h。如果是,为什么h->next->数据可用,如果h是免费的。当然,"第二个"节点没有释放。但是,由于删除了头,它应该能够引用下一个元素。这里的错误是什么?
释放列表的迭代函数:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
该功能的作用如下:
检查
head
是否为NULL,如果为,则列表为空,我们只返回将
head
保存在tmp
变量中,并使head
指向列表上的下一个节点(这在head = head->next
中完成- 现在我们可以安全地使用
free(tmp)
变量,并且head
只指向列表的其余部分,返回步骤1
只需迭代列表:
struct node *n = head;
while(n){
struct node *n1 = n;
n = n->next;
free(n1);
}
一个函数可以完成这项工作,
void free_list(node *pHead)
{
node *pNode = pHead, *pNext;
while (NULL != pNode)
{
pNext = pNode->next;
free(pNode);
pNode = pNext;
}
}
struct node{
int position;
char name[30];
struct node * next;
};
void free_list(node * list){
node* next_node;
printf("nn Freeing List: n");
while(list != NULL)
{
next_node = list->next;
printf("clear mem for: %s",list->name);
free(list);
list = next_node;
printf("->");
}
}
你总是可以递归地这样做:
void freeList(struct node* currentNode)
{
if(currentNode->next) freeList(currentNode->next);
free(currentNode);
}
int delf(Node **head)
{
if(*head==NULL)
{
printf("Emptyn");
return 0;
}
else
{
Node *temp=*head;
*head=temp->next;
free(temp);
}
return 0;
}
while(head!=NULL)
{
delf(&head);
}