c - double free or corruption (fasttop) 错误 c/c++ linux

标签 c memory-management linked-list

谁能解释为什么我在 print_list(head_node) 之后立即在该程序中出现“double free or corruption (fasttop)”错误? head_node = insert_to_first(head_node, temp);之前,head_node已经指向其他节点。例如head_node -> node1 我想要的是在 node1 之前插入一个节点,该节点将由 head_node 指向并将指向 node1. 完整程序如下:(使用g++编译)

#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/

相关文章:

释放后还能打印字符串吗?

c++ - C++中的静态和动态内存分配

c - 以有序的方式在链表中间插入一个元素?

c++ - 链表中节点的字段未解析

java - HackerRank 扫描器类 Java

java - C 结构和 Java 类之间有什么区别?

c - 为什么输出错误?

php - 已用完 X 字节的允许内存大小

java - 从 C 而不是 Java 管理 Android 应用程序设置?

c - Rust,如何与 gethostname() std::libc 交互