0

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Matthew
  • 105
  • 1
  • 11
  • There is a bug somewhere in the code you didn't show. You need to show a [MCVE]. BTW: in C parameters are passed by value, so if you call `xyz = dequeue(somequeue);` then `somequeue` won't be modified. That may be your problem. – Jabberwocky Dec 13 '17 at 11:28

2 Answers2

2
 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

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
1

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Yes, I can't believe I didn't remember that, thank you. Why is the first declaration of the struct invalid ? – Matthew Dec 13 '17 at 12:10
  • @Matthew It declares two different structures. The first one is unnamed and the second one is incomplete. The compiler should issue a diagnostic message at least for this statement q = q->next; – Vlad from Moscow Dec 13 '17 at 12:11
  • I understand, thank you ! – Matthew Dec 13 '17 at 13:26