【发布时间】:2011-09-19 00:25:14
【问题描述】:
如何释放在另一个函数中分配的节点?
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 %d\n", h->next->data);
return 0;
}
我想释放头部、第二个和第三个变量。
谢谢。
更新:
int main()
{
struct node* h = buildList();
printf("The element is %d\n", h->next->data); //prints 2
//free(h->next->next);
//free(h->next);
free(h);
// struct node* h1 = buildList();
printf("The element is %d\n", h->next->data); //print 2 ?? why?
return 0;
}
两个打印 2. 不应该调用 free(h) 删除 h。如果是这样,为什么 h->next->data 可用,如果 h 是免费的。当然,“第二个”节点没有被释放。但是由于 head 被移除,它应该能够引用下一个元素。这里有什么错误?
【问题讨论】:
-
您是否在取消链接或释放它们时遇到问题?如果是后者,则使用来自
malloc()的返回值调用free()。 -
user349433:这不是硬件,我尝试在 main 中使用 free(h)。那么如果 h 不存在,那么 h->next->data 怎么会给出值 2?于是我问。但是 free(h->next) 也应该被调用。但是既然h是头,去掉头后,我肯定不能引用头->下一个,不是吗。我哪里弄错了?
-
free()不会擦除内存中的内容,它只是允许这些内容以后再使用。巧合的是,指针h->next仍然有效,因为您free()'d 的内存尚未被重用。 -
@jase21 Well Heath 回答了这个问题。它只是在您尝试时有效,但不能保证它在将来或在另一台机器上也能正常工作。在另一台机器上做
h->next->data可能会给你带来分段错误。好的,假设您有h具有以下数据:h->next = 0x12341281; h->data = 1,当您执行free(h)时,您只需让机器知道将来malloc您可以覆盖h,h不是更多地被您的程序使用。但是h->next = 0x12341281; h->data = 1的数据似乎一直存在,这并不意味着您应该使用它们。 -
@jase21 也许在将来
malloc,其中h->next和h->data被保存,将写入其他内容。然后在执行h->next->data时会出现分段错误。
标签: c linked-list heap-memory