I have an assignment to write a Stacks class using a list and a Queue class using two Stacks. I've completed the assignment, but running the valgrind I find that I have a memory leak in the following code:
T Stack<T>::pop()
{
T *n = new T;
*n = myStack.front();
myStack.pop_front();
return *n;
}
I can't delete the pointer after I return it so I'm not sure how to fix it. Thanks in advance.
Why do you even need to use new? You can make a copy of the stack's top value like this:
T Stack<T>::pop()
{
T n = myStack.front();
myStack.pop_front();
return n;
}
So there are no allocations and no leaks;
Make a copy and then clear the memory if any inside pop_front.
T Stack<T>::pop()
{
T ret = myStack.front();
myStack.pop_front();
return ret;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With