双重免费或损坏(fasttop)错误c/c++;linux

双重免费或损坏(fasttop)错误c/c++;linux,c,memory-management,linked-list,C,Memory Management,Linked List,有人能解释一下为什么我在打印列表(head\u节点)之后立即在这个程序中出现“双重免费或损坏(fasttop)”错误吗?在头节点之前=首先将头节点插入头节点(头节点,临时),头节点已指向其他节点。e、 g.head\u node->node1我想要的是在node1之前插入一个节点,它将由head\u node指向node1。 下面是完整的程序:(使用g++编译) #包括 #包括 typedef结构节点; 结构节点{ int数据; 节点*下一步; }; 节点*创建_项(int); 节点*首先将_插

有人能解释一下为什么我在打印列表(head\u节点)之后立即在这个程序中出现“双重免费或损坏(fasttop)”错误吗?在
头节点之前=首先将头节点插入头节点(头节点,临时)
头节点
已指向其他节点。e、 g.
head\u node->node1
我想要的是在
node1
之前插入一个节点,它将由
head\u node
指向
node1
。 下面是完整的程序:(使用g++编译)

#包括
#包括
typedef结构节点;
结构节点{
int数据;
节点*下一步;
};
节点*创建_项(int);
节点*首先将_插入_(节点*,节点*);
作废打印列表(节点*);
int main(){
结构节点*头节点;
结构节点*temp;
head_节点=创建_项(2);
temp=创建项目(5);
头节点=首先将头节点插入头节点(头节点,临时);
打印列表(表头节点);
自由(头节点);
免费(临时);
返回0;
}
节点*创建_项(整数数据){
Node*new_item=(Node*)malloc(sizeof(Node));
(*新建项目)。数据=数据;//新建项目->数据=数据;
新建项目->下一步=空;
返回新项目;
}
节点*首先插入到节点(节点*头节点,节点*项){
项目->下一步=头节点;
退货项目;
}
作废打印列表(节点*节点){
printf(“正在执行…\n”);
对于(;node!=NULL;node=node->next){
printf(“当前列表(地址):\t%p\n”,节点);
printf(“数据:\t\t\t%d\n”,节点->数据);
printf(“下一个列表(地址):\t%p\n”,节点->下一个);
printf(“--------------------------------------\n”);
}
printf(“执行终止。\n”);
}
提取您的代码:

head_node = create_item(2);
temp = create_item(5);

head_node = insert_to_first(head_node, temp);
// now head_node has changed, it points now to the same location as temp now

free(head_node);  // so here you are not freeing the original head_node, but rather temp
free(temp);       // and here you free temp again, hence the "double free".

这是因为在行
head\u node=insert\u to\u first(head\u node,temp)之后
head\u节点
指向与
temp
相同的元素。您应该编写一个类似于
print_list
delete_list
函数,释放每个元素而不是打印它。OP基本上,您的
insert_to_first
函数添加到列表的开头,并返回新插入的指针作为标题。执行此操作时:
head\u node=首先将\u插入到\u(head\u node,temp)
头节点和临时指针都指向同一位置。所以当你做
free时(head\u节点);免费(临时)这是你的双人免费。相反,您应该编写一个函数来释放整个列表,方法与编写
print\u list
类似,但
head\u node
将指向
temp
之后的
insert\u-to\u-first(node*,node*)
?@narutuzumaki是的,请参阅下面的答案。你自己也可以很容易地检查。可能是好的,现在我知道了。谢谢
head_node = create_item(2);
temp = create_item(5);

head_node = insert_to_first(head_node, temp);
// now head_node has changed, it points now to the same location as temp now

free(head_node);  // so here you are not freeing the original head_node, but rather temp
free(temp);       // and here you free temp again, hence the "double free".