Reputation:
I'm studyind dinamic lists in C and this is a queue that I made using structs and pointers, it is queueing the nodes normally but when I call the Dequeue and Show methods in that order, it enter in a loop and displays weird random numbers.
struct Node { int data; struct Node *next; }; typedef struct Node node; int size = 0; node* front = NULL; node* rear = NULL;
//adds a new node at the end of the list void Enqueue(int n){
node *new_node = (node*)malloc(sizeof(node)); new_node->data = n; new_node->next = NULL; if (front == NULL && rear == NULL){ front = new_node; rear = new_node; return; } rear->next = new_node; rear = new_node; }
//when calling this method before show(), the loop issue occurs void Dequeue(){
node *tmp = front; if (front == rear){ front = rear = NULL; } else { front = front->next; } free(front); } //if just calling Enqueue() and Show() methods, it runs normally void Show(){ node *tmp = front; while(tmp != NULL){ printf("%d \n", tmp->data); tmp = tmp->next; } } int main(void){ Enqueue(1); Enqueue(2); Enqueue(3); Dequeue(); Show(); system("pause"); return 0; }
Upvotes: 0
Views: 233
Reputation: 272
free(front); // SHOULD BE `free(tmp)`
The correct code
void Dequeue(){
node *tmp = front;
if (front == rear)
front = rear = NULL;
else
front = front->next;
free(tmp);
}
Upvotes: 1
Reputation: 3688
Check your Dequeue(...)
function. You're freeing the node on the front after re-assigning it. Try this instead
void Dequeue(){
node *tmp = front;
if (front == rear){
front = rear = NULL;
}
else {
front = front->next;
}
free(tmp);
}
Upvotes: 1
Reputation: 125007
free(front);
I think you mean:
free(tmp);
Just before your call to free()
, you reassign front
to point to the new head of the queue, so freeing that node isn't what you want to do. tmp
is a copy of the pointer to the original head node, and it's safe to free that one after you've reassigned front
.
Upvotes: 0