gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:33:18 28 4
gpt4 key购买 nike

我尝试实现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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com