谁能解释为什么我在 print_list(head_node)
之后立即在该程序中出现“double free or corruption (fasttop)”错误? 在
完整程序如下:(使用g++编译)head_node = insert_to_first(head_node, temp);
之前,head_node
已经指向其他节点。例如head_node -> node1
我想要的是在 node1
之前插入一个节点,该节点将由 head_node
指向并将指向 node1
.
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE Node;
struct NODE {
int data;
Node* next;
};
Node* create_item(int);
Node* insert_to_first(Node*, Node*);
void print_list(Node*);
int main() {
struct NODE *head_node;
struct NODE *temp;
head_node = create_item(2);
temp = create_item(5);
head_node = insert_to_first(head_node, temp);
print_list(head_node);
free(head_node);
free(temp);
return 0;
}
Node* create_item(int data) {
Node* new_item = (Node*) malloc(sizeof(Node));
(*new_item).data = data; // new_item->data = data;
new_item->next = NULL;
return new_item;
}
Node* insert_to_first(Node* head_node, Node* item) {
item->next = head_node;
return item;
}
void print_list(Node* node) {
printf("Executing...\n");
for(; node != NULL; node = node->next) {
printf("Current list (address):\t%p\n", node);
printf("Data:\t\t\t%d\n", node->data);
printf("Next list (address):\t%p\n", node->next);
printf("-----------------------------------------\n");
}
printf("Execution terminated.\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".
关于c - double free or corruption (fasttop) 错误 c/c++ linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49924755/