Reputation: 3974
I am new to using threads, and I thought a good excercise would be to write a queue that works with threads. However, something is wrong, I suspect that the consumer threads try to access the same data or something. I use mutexes but I probably has misunderstood something...
I get this error (about every third run):
*** glibc detected *** ./t_queue_test: double free or corruption (fasttop): 0x0000000002114610 ***
The code is rather long so I've posted it on pastebin, but if thats incorrect, I can paste it here.
t_queue.h -> http://pastebin.com/2KYmujeE
t_queue.c -> http://pastebin.com/1wZPMwDB
t_queue_test.c -> http://pastebin.com/QKCTQWaf
I thinks the error occures in function 'get_q', and I've marked it in the code.
Thanks for any pointers or suggestions. I've digged around stackoverflow for similar questions, and I will dig some more! Valgrind doesn't show anything yet either.
Upvotes: 0
Views: 2033
Reputation: 180917
Just a note for later in case pastebin goes away; the faulty code is this;
if(q->rear != NULL && q->front != NULL)
{
node_n = q->front;
*d = node_n->data;
q->front = node_n->next;
free(node_n);
}
It cleans up the front quite ok, however if the last element is removed, rear also needs to be updated to reflect the queue being empty. For example, this will do it;
if(q->rear != NULL && q->front != NULL)
{
node_n = q->front;
*d = node_n->data;
q->front = node_n->next;
if(q->front == NULL)
q->rear = NULL;
free(node_n);
}
Upvotes: 1