I’m trying to delete all nodes from my queue of structures.
Structure:
struct element{
int id;
int sign;
int year;
int month;
double amount;
struct element *next;
};
struct queue{
struct element *head;
int size;
};
And the function I wrote:
void delete(struct queue *queue) {
if (queue->size == 0){
printf("Structure is empty\n");
}
else {
struct element* this;
struct element* other;
for(this=queue->head;this!=NULL;this=other)
{
other=this->next;
free(this);
}
free(queue);
}
}
It doesn’t work, and I’m out of ideas. Any suggestions?
In your
deleteroutine, you do not free thequeueif the size is empty, but you do free it if the size is non-empty. You should probably do the same for both cases. That is, either don’t free in both places, or free in both places.It is bothersome to need to figure out what the right thing to do is, because
deletecan not know how thequeuewas allocated. Given your current design, a way out may be to pass a flag todeleteto indicate what it should do: