c - 自由函数激活断点

标签 c linked-list free

我试图调用 free 函数来从链表中释放节点,但每当我尝试这样做时,IDE (CLion) 都会停止程序并给我一个 SIGTRAP(跟踪/断点陷阱)。

这是链接列表:

struct node{
    int score;
    int index;
    struct node* nextNode;
};

typedef struct node* List;

现在是初始化和链接列表的函数:

List list= malloc(sizeof(List));
list->index=-1;
list->score=-10;
list->next=NULL;
min++;  min--;
List temp;
for(int i=sizeGrafi-1; i>0; i--){
     temp= malloc(sizeof(List));
     temp->index=i;
     temp->score=-10;
     temp->next=list;
     nodiDaVisitare=temp;
}

这是应该删除和取消分配节点的函数(为了避免无用的代码,我将 只需发布要删除的节点是头的情况):

List removeNode(List list){
    Lista temp= malloc(sizeof(List));
    temp=list;
    list=list->next;
    free(temp);
    return list;
}

我尝试查看类似的问题,但我找不到我的代码有什么问题。当调用 free 函数时会发生崩溃。

编辑:我按照建议删除了 typedef

typedef struct node* List;

,将所有列表重写为Node*,Node定义为:

typedef struct node{
    int punteggio;
    int indice;
    struct nodo* successivo;
}Node;

并在 malloc 中使用正确的大小(即 sizeof(Node))。 现在 free 功能似乎没有任何问题。谢谢大家。

最佳答案

    Lista temp= malloc(sizeof(List));
    temp=list;
    list=list->next;

malloc内存并将其引用存储在temp中。然后用 list 分配 temp。之前的值丢失。

然后你尝试释放该指针 - 因此free出现问题。

顺便说一句,这个函数根本没有任何意义。很难理解你想要实现什么。

此外,切勿将指针隐藏在 typedef 后面。

关于c - 自由函数激活断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68397646/

相关文章:

c - 通过函数传递时指向 NULL 的全局链表

java - 从文件加载和保存链表

linux - free -g 与 sed -n 加第 n 个字符

c - 在 C 中使用 Free() 时的运行时错误

c++ - 如何释放使用 C++ "new"运算符分配的 C 中的内存

c++ - 能不能用g++编译代码用Solaris Studio的Performance Analyser做性能分析?

MySQL 通过 SSH + Bash 错误

c - printf() 格式化为十六进制

c++ - 如何在 Windows Phone 8.1 中通过蓝牙连接发送字符

java - 链表 : What to substitute for node on the last node?