【发布时间】:2018-07-27 13:29:07
【问题描述】:
我正在使用 C 中的通用链表实现一个队列,其中列表中的每个节点都是一个简单的结构,其中包含一个 void 指针和一个指向下一个节点的节点指针。在出队操作中,我想删除头(工作正常),但我也想在删除后返回该节点。
编辑澄清
我在 dequeue 函数中所做的是(示例):
//This is my queue struct
typedef struct Queue{
LinkedList* list;
size_t item_size;
} Queue;
//this is the dequeue function
Node* dequeue(Queue* queue){
Node* head = queue->list->head;
Node* returnedValue = (Node*)malloc(sizeof(Node));
memcpy(returnedValue, head, sizeof(Node));
removeBegin(queue->list);
return returnedValue;
}
//this is the remove head function
void removeBegin(LinkedList* list){
Node* tempHead = list->head;
list->head = list->head->next;
tempHead->next = NULL;
free(tempHead->value);
tempHead->value = NULL;
free(tempHead);
tempHead = NULL;
}
问题是在 free 功能正常之前的一切。一切都被正确复制。但是在 free 函数调用之后,复制到新分配节点的值立即变成垃圾(或 0)。
我调用函数的方式就是使用这个函数初始化队列:
Queue* init_queue(size_t size){
Queue* queue = (Queue*)malloc(sizeof(Queue));
// int x = 10;
queue->list = createList(NULL, size);
return queue;
}
然后调用 dequeue 并将队列的指针传递给它。
我该如何解决这个问题? 非常感谢。
【问题讨论】:
-
请说明您是如何调用
copyValue的,问题很可能出在那里。阅读:minimal reproducible example. -
哦,现在(我想)我明白了。当然,复制的值变得无效,因为您释放了它。仍然显示minimal reproducible example。
-
函数名有点用词不当——它实现了一个复制和释放(或移动)而不是复制
-
不清楚你为什么要这样做。与其复制节点,您肯定只需要它包含的值吗?
-
您在
memcpy()调用中使用 n1->value 作为目标指针,而没有将其设置为任何内容。尝试改用calloc(),您更有可能得到段违规,从而告诉您真正的问题出在哪里。