I’m working through some C exercises (newbie) I hit a bit of a problem. I was given a first in first out queue and told to modify the remove function to be FILO.
This works fine when I leave out the free((void *) p); line inside the while loop, I took this line from the previous method. Can anyone tell me why it doesn’t work when this line is there? I’m guessing I can’t remove it entirly due to memory leaks?
/* remove next Item from queue, placing it in the 2nd argument;
* return 1/0 if successful/queue empty */
int q_remove(Queue *q, Item i) {
struct q_element *p;
if (q->head == NULL)
return 0;
if(q->head==q->tail){
p=q->head;
q->head=NULL;
q->tail=NULL;
memcpy(i, p->value, q->size);
free(p->value);
free((void *) p);
return 1;
}
p=q->head;
while(p != NULL){
if(p->next==q->tail){
memcpy(i, p->next->value, q->size);
free(p->next->value);
q->tail=p;
q->tail->next=NULL;
free((void *) p);
return 1;
}
p=p->next;
}
return 0;
}
The lines:
…should probably be
because you’re not trying to free ‘p’ (which is your new ‘tail’), but the element p->next which was you’re old tail. Set the pointer to null after you’ve free’d it. The value q->tail already points to ‘p’ and it isn’t valid to free ‘p’ at after that, since ‘p->next’ is what you’re trying to remove.
That might be it.
Also, I don’t personally like how you’ve typedef’d ‘Item’ as a void* somewhere, it looks confusing because ‘Item’ looks like a passed-by-value variable on the stack.
Kev