void insert_queue (queue *this, queue_item_t item) {
//Inserts a new item at the end of queue.
queue_node *temp = malloc(sizeof (struct queue_node));
temp->item = item;
if (isempty_queue(this)) this->front = temp;
else this->rear->link = temp;
this->rear = temp;
//free(temp);
}
queue_item_t remove_queue (queue *this) {
assert (! isempty_queue (this));
//This removes the first item from queue.
queue_item_t temp = this->front->item;
this->front = this->front->link;
return temp;
}
У меня возникает ошибка сбоя seg, когда я пытаюсь освободить «temp». Я должен освободить узел после его использования, не так ли? Итак, как я могу предотвратить утечку памяти в этой ситуации? Есть идеи? Спасибо.Освобождение памяти в C: Очередь
Когда я удаляю бесплатный (темп), все работает нормально, но я получаю утечки памяти. Я не уверен, куда положить бесплатно, если он не принадлежит этой функции. Я также добавил функцию удаления. Должен ли свободен войти сюда?
EDIT EDIT: Спасибо всем, вот мой обновленный код.
queue_item_t remove_queue (queue *this) {
assert (! isempty_queue (this));
queue_node *temp = this->front;
queue_item_t rVal = temp->item;
//Moves on to the next one.
this->front = this->front->link;
//Free the unlinked node.
//free(temp->item); <<<<---- This causes program to fail.
free(temp);
return rVal;
}
Утечки памяти все еще встречаются.
Подумайте о том, что произойдет, если это -> задний == this-> front в remove_queue. –
@CharlieBurns +1, обратите внимание, что он не должен проверять * это * сравнение, но он должен проверить * что-то *. Если после этого происходит 'this-> front == nullptr', это действие = this = back = nullptr;'. – WhozCraig