简体   繁体   English

如何防止广义链表中的 memory 泄漏?

[英]How to prevent memory leak in generalized linked list?

I've implemented my own linked list data structure.我已经实现了自己的链表数据结构。 Data is stored inside Node struct.数据存储在Node结构中。 Code is as follows代码如下

// NODE

template <typename T>
struct Node
{
    T data;
    Node<T> *next;
    Node(T);
};

template <typename T>
Node<T>::Node(T d) : data(d), next(NULL) {}
// LIST

#include "node.cpp"

template <typename T>
class List
{
    Node<T> *head;
    int size;

public:
    List();                       // Default constructor
    List(const List &);           // Copy constructor
    void push_back(const T &);    // Insert element to the end of the list
    int get_size() const;         // Get the current size of the list
    T &operator[](int) const;     // Overload [] operator
    void operator=(const List &); // Overload = operator
    ~List();                      // Destructor
};

template <typename T>
List<T>::List() : head(NULL), size(0) {}

template <typename T>
List<T>::List(const List &list) : head(NULL), size(0)
{
    for (int i = 0; i < list.size; i++)
        push_back(list[i]);
}

template <typename T>
void List<T>::push_back(const T &data)
{
    // Create new Node with data
    Node<T> *nn = new Node<T>(data);

    // Find insert position
    if (head == NULL)
    {
        head = nn;
        size++;
        return;
    }

    Node<T> *traverse = head;
    while (traverse->next)
        traverse = traverse->next;

    // Traverse points to end of the list
    traverse->next = nn;
    size++;
}

template <typename T>
int List<T>::get_size() const
{
    return size;
}

template <typename T>
T &List<T>::operator[](int index) const
{
    int count = 0;
    Node<T> *traverse = head;
    while (traverse && count < index)
    {
        traverse = traverse->next;
        count++;
    }
    return traverse->data;
}

template <typename T>
void List<T>::operator=(const List<T> &list)
{
    Node<T> *traverse = head;

    while (head)
    {
        traverse = head;
        head = head->next;
        delete traverse;
    }

    size = 0;
    for (int i = 0; i < list.getSize(); i++)
        push_back(list[i]);
}

template <typename T>
List<T>::~List()
{
    Node<T> *traverse = head;

    while (head)
    {
        traverse = head;
        head = head->next;
        delete traverse;
    }
}

Problem is with memory leak.问题在于 memory 泄漏。 Consider the following main file考虑以下main文件

#include "list.cpp"

using namespace std;

List<int *> l;

void func()
{
    int *i = new int[2];
    i[0] = 1;
    i[1] = 2;
    l.push_back(i);
}

int main()
{
    func();
    return 0;
}

This program has memory leak according to Valgrind.根据 Valgrind,该程序有 memory 泄漏。 It is because that Node does not have a destructor so it can not delete data inside it.这是因为该Node没有析构函数,所以它不能删除其中的data However, I can not add a destructor to Node because, suppose that I am using List<int> so it is an error to delete something that was not dynamically allocated.但是,我无法向Node添加析构函数,因为假设我正在使用List<int>因此删除未动态分配的内容是错误的。 In short, whenever I use a dynamically allocated data type for List , I get memory leak.简而言之,每当我为List使用动态分配的数据类型时,我都会得到 memory 泄漏。 How can I overcome this situation?我该如何克服这种情况? Thanks.谢谢。

The leak in your example has nothing to with the list.您示例中的泄漏与列表无关。 You leak the same with:你泄漏同样的:

void func()
{
    int *i = new int[2];
    i[0] = 1;
    i[1] = 2;
}

You have to delete what you created via new and delete[] what you created via new[] .您必须delete通过new创建的内容并delete[]通过new[]创建的内容。 To fix the leak:要修复泄漏:

void func()
{
    int *i = new int[2];
    i[0] = 1;
    i[1] = 2;
    l.push_back(i);
    delete [] i;
}

However, note that then after the delete[] you have a dangling pointer in the list.但是,请注意,在delete[]之后,列表中有一个悬空指针。

It is not the List s buisness to delete objects when you push raw pointers to it.当您将原始指针推送到它时,删除对象不是List的业务。 The list cannot know if those are owning pointers or not.该列表无法知道这些是否拥有指针。 For example:例如:

void func()
{
    int i = 0;
    l.push_back(&i);
}

No need to delete anything here.这里不需要删除任何东西。 (Though, same here: once the function returns you have a dangling pointer in the list) (虽然,这里相同:一旦 function 返回您的列表中有一个悬空指针)

Neither of the abvove is really "ok".以上都不是真的“好的”。 Don't use raw owning pointers.不要使用原始的拥有指针。 Use smart pointers instead.请改用智能指针。 And if you want a list of integers then use a List<int> (or rather a std::list<int> ).如果你想要一个整数列表,那么使用List<int> (或者更确切地说是std::list<int> )。

Use std::unique_ptr as the data type for the nodes, eg:使用std::unique_ptr作为节点的数据类型,例如:

List<std::unique_ptr<int[]>> l;

When each node is destroyed, its destructor will destroy its unique_ptr data, which will in turn call delete[] on the int* pointer it is holding.当每个节点被销毁时,其析构函数将销毁其unique_ptr数据,这将依次在其持有的int*指针上调用delete[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM