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