Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak in stacks/queues c++

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.

like image 226
user1740222 Avatar asked Dec 07 '25 13:12

user1740222


2 Answers

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;

like image 70
Lyubomir Vasilev Avatar answered Dec 10 '25 04:12

Lyubomir Vasilev


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;
    }
like image 39
Ram Avatar answered Dec 10 '25 04:12

Ram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!