c - 如何释放结构体c中的双指针?

标签 c pointers struct free

我尝试实现Queue。在我的deleteq函数中,我只想释放指向另一个结构(队列元素)的指针并返回指向已删除元素的值的指针,但free函数会导致错误:段错误。

struct Node{
   void* val;
   struct Node* next;
};

typedef struct Queue{
    struct Node* head;
    struct Node* tail;
}Queue;

Queue nw_queue(void* val){
    struct Node *node_ptr = (struct Node*)malloc(sizeof(struct Node));
    node_ptr->val = val;
    node_ptr->next = NULL;
    Queue q;
    q.head = node_ptr;
    q.tail = node_ptr;
    return q;
}



void add(Queue *q, void* val){
    struct Node *node_ptr = (struct Node*)malloc(sizeof(struct Node));
    node_ptr->val = val;
    node_ptr->next = NULL;
    if (empty(*q)){
        *q = nw_queue(val);
        return ;
    }
    q->tail->next = node_ptr;
    q->tail = node_ptr;
}

void* deleteq(Queue* q_ptr){
    if (empty(*q_ptr)){
        puts("Error deleteq:Empty queue");
        return NULL;
    }
    struct Node* cur_head = q_ptr->head;
    q_ptr->head = q_ptr->head->next;
    struct Node** toFree = &(cur_head->next);
    free(toFree); //Error
    return cur_head->val;
}

int main()
{
    int a = 5;
    Queue q = nw_queue(&a);
    add(&q, &a);
    deleteq(&q);
    return 0;
}

最佳答案

我不明白你想达到什么目的,但以下肯定是错误的

struct Node** toFree = &(cur_head->next);
free(toFree); //Error

您正在释放一个堆栈地址,而不是malloc()/calloc()/返回的指针realloc(),您传递给 free() 的任何其他内容都是未定义的行为。

因此解决方法是,仅将 malloc()calloc()realloc 的任何内容传递给 free() ()动态分配的内存

为什么我这么确定上面的代码是错误的?因为 & 会给你某个东西的地址,那当然是一个指针,但不是由 malloc()calloc()realloc() 这是唯一允许被free()ed的函数。

关于c - 如何释放结构体c中的双指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49798991/

相关文章:

c - 在链表的开头插入新节点

c - Win32 : Accessing a partition beyond the end of a volume?

c - 返回计算翻译的程序的结构

c++ - 在哪里声明结构运算符重载

c++ - 从 'const X*' 到 'X*' 的错误无效转换

c - strcpy:在 union 中使用 char** 变量作为参数

c++ - 为什么用nar-maven编译静态库时要加compiler option/MD?

c - C 中结构体数组初始化为 0,警告 : missing braces around initializer

c - 结构程序停止,没有任何错误

c - C 中的指针。需要解释这个小代码