I was deallocating a linked list, but go a read access violation. In my destructor's loop, when I was stepping through the code, I noticed the violating was in the second loop iteration. Here is my code.
The problem is that current and temp points to the same node. After you have deallocated the node pointed to by current you can't use temp for the same reason you can't use current.
Changing the code to what "closed account" suggested improves things. The temp pointer is then the pointer to the next node after current so you may want to rename it next to better describe what it is.
Anyhow, you still have a problem that the loop stops too early. As soon as there is no node after the current node the loop stops which means the last node never gets deallocated. To fix this you would have to change the loop condition slightly.
If you provide a constructor (where you initialize the members) and a destructor (where you delete next) you wouldn't need a loop in the Stack destructor. Only delete m_head.
It would probably be better for top() to return a reference rather than a value. Also, push() should take a const reference rather than a value as the argument.
The code will break if someone copies one list to another. Consider adding the copy constructor and assignment operator.
int main()
{
Stack<int> stack;
stack.push(33);
stack.push(22);
stack.push(32);
stack.push(21);
stack.pop();
stack.pop();
stack.pop();
stack.pop();
// the stack is now empty, but none of the memory was freed.
}
template<class T> void Stack<T>::pop()
{
if (m_head != nullptr)
{
m_head = m_head->next; // You overwrite the m_head pointer, but you need to free the memory beforehand
--m_size;
}
elsethrow Stack_Exception{ "Stack::pop: Attempted to deference invalid node!" };
}