【发布时间】:2016-09-29 16:50:16
【问题描述】:
我写了一个函数来在链表的末尾添加动态创建的节点,使用 malloc。然后在函数的最后一行,我尝试为指针 temp 释放内存空间。
addnodelast(int data){
struct node* temp =(struct node*)malloc(sizeof(struct node));
temp->data=data;
temp->link=NULL;
struct node*p=head;
while(p->link!=NULL)
{
p=p->link;
}
p->link=temp;
free(temp);
}
但是在执行时,我无法打印列表,因为它无限打印随机值。但是当我删除/注释最后一行 free(temp) 时,一切正常。
【问题讨论】:
-
我在这段代码中看不到任何打印。而且,我在这里根本看不到任何有意义的东西。
-
释放刚刚添加的节点是逻辑错误。
-
你过早地打电话给
free()。
标签: c linked-list malloc free