I am trying to make my queue library and when I implement the dequeue method, an exception is throw "0xC0000374: A heap has been corrupted (parameters: 0x77475910)." This only gets thrown AFTER I already remove an item from the queue, the item is returned successfully however the first element is not removed, here is how I wrote the code :
typedef struct {
int value;
struct queue_item * next;
} queue_item;
typedef queue_item * queue;
and this is the method:
int dequeue(queue q)
{
queue fi = q;
int value = q->value;
fi = q;
q = q->next;
free(fi);
return value;
}
int dequeue(queue q)
{
queue fi = q;
You pass q
by value so even though you make q
point to next element inside dequeue()
, outside dequeue()
, it is still pointing to freed memory and using q
will crash.
Pass a pointer to q
to dequeue
For starters this declaration
typedef struct {
int value;
struct queue_item * next;
} queue_item;
is invalid.
It should look like
typedef struct queue_item {
int value;
struct queue_item * next;
} queue_item;
The function dequeue
deals with a copy of the original queue pointer because it is passed to the function by value.
So this statement in the function
q = q->next;
does not change the original pointer.
You should pass the pointer by reference. For example
int dequeue(queue *q)
{
queue fi = *q;
int value = ( *q )->value;
*q = ( *q )->next;
free( fi );
return value;
}
User contributions licensed under CC BY-SA 3.0