I am implementing a queue using a generic linked list in C where each node in list is a simple struct which contains a void pointer and a node pointer to the next node. In the dequeue operation I want to remove the head (which is working fine), but I also want to return that node after it is removed.
EDITED TO CLARIFY
What i did in the dequeue function is (example):
//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;
}
the problem is everything before the free function is ok. Everything is being copied correctly. But immediately after the free function call the value that is copied to the newly allocated node becomes garbage (or 0).
The way I call the function is simply initialize the queue using this function:
Queue* init_queue(size_t size){
Queue* queue = (Queue*)malloc(sizeof(Queue));
// int x = 10;
queue->list = createList(NULL, size);
return queue;
}
then call dequeue and pass it the pointer of the queue.
How can I solve this? thanks a lot.