Hello,
So I am editing a project I had where I was creating a queue. In my pop() method I am having an issue and I am not sure why. I am trying to free the memory of the Node I am popping from the queue and also returning the data from that Node to the user before it is deleted. When I comment out the free() method in the pop() method it works and when I uncomment the free() call I get heap memory crashes. Can anyone please help me see what I am doing wrong?
Queue.inl
template <typename T>
T Queue<T>::pop()
{
if (isEmpty())
{
std::cout << "pop() was used, but the Queue is empty.\n\n";
return NULL;
}
else
{
Node * temp = headNode;
T removedItem = temp->data;
headNode = headNode->nextNode;
std::cout << "pop() was used and " << temp->data << " was removed from the Queue.\n\n";
free(temp);
size--;
return removedItem;
}
}
Queue.h
#pragma once
template <class T>
class Queue
{
public:
Queue();
Queue(T newItem);
void push(T newItem);
void pop_all();
T pop();
T peek();
bool isEmpty();
int getSize();
private:
struct Node
{
T data;
Node * nextNode;
};
Node LinkedList;
Node * headNode; // front of the queue
Node * tailNode; // End of the Queue
int size;
};
#include "Queue.inl"