C ++类链接列表内存泄漏

时间:2016-05-15 08:18:27

标签: c++ memory-leaks linked-list

嗨我遇到2个内存泄漏问题我似乎无法修复我已经评论了代码中泄漏似乎是问题所在。

标题 main.cpp中

#include <iostream>
#include <string>
#include "MyList.h"

// NODE FUNCTIONS //

template<class T>
void MyList<T>::push_front(T & newData)
{
    Node<T> *temp = new Node<T>; // CAUSES MEMORY LEAK... delete temp does not work
    temp->setData(newData);
    temp->setNext(NULL);
    if (isEmpty() == true)
    {

        temp->setNext(head);
        head = temp;
        tail = head;
    }
    else
    {

        temp->setNext(head);
        head = temp;
    }

}

template<class T>
void MyList<T>::push_back(T & newData)
{
    Node<T> *temp = new Node<T>; // CAUSES MEMORY LEAK... delete temp does not work
    temp->setData(newData);
    temp->setNext(NULL);
    if (isEmpty() == true)
    {
        temp->setNext(head);
        head = temp;
        tail = head;
    }
    else
    {
        tail->setNext(temp);
        tail = temp;
    }

}

template<class T>
void MyList<T>::pop_front()
{

    if (isEmpty() == true)
    {
        std::cout << "Nothing to pop" << std::endl;
    }
    else
    {
        Node<T> *temp = head;
        head = temp->getNext();

    }
}

template<class T>
void MyList<T>::pop_back()
{
    if (isEmpty() == true)
    {
        std::cout << "Nothing to pop" << std::endl;
    }
    else if (head == tail)
    {
        head = tail = NULL;
    }
    else
    {
        Node<T> *temp = head;

        while (temp->getNext() != tail)
        {
            temp = temp->getNext();
        }
        temp->setNext(NULL);
        tail = temp;
    }

}

我尝试将问题区域更改为:Node * temp;然而,由于没有初始化,它不起作用。我已经尝试多次更改我的解构函数到没有更改,我完全丢失,因为代码工作正常并且列表打印正常我只有2个内存泄漏问题

1 个答案:

答案 0 :(得分:0)

您问题的即时解决方案(甚至不了解您的设计)是使用c++11标准中已存在的smart pointers

如果您不使用c++11,则可以使用RAII实现自己的智能指针(示例为here

修改

修正当前代码的提案:

template<class T>
void MyList<T>::pop_front()
{

    if (isEmpty() == true)
    {
        std::cout << "Nothing to pop" << std::endl;
    }
    else
    {
        Node<T> *temp = head;
        head = temp->getNext();
        delete temp; // <-- remove the ORIGINAL head from the memory
    }
}

template<class T>
void MyList<T>::pop_back()
{
    if (isEmpty() == true)
    {
        std::cout << "Nothing to pop" << std::endl;
    }
    else if (head == tail)
    {
        head = tail = NULL;
    }
    else
    {
        Node<T> *temp = head;

        while (temp->getNext() != tail)
        {
            temp = temp->getNext();
        }
        temp->setNext(NULL);
        delete tail; // <-- removing the ORIGINAL tail from the memory
        tail = temp;
    }
}