首页 > 解决方案 > C++:链表中的潜在内存泄漏

问题描述

我正在写一个链表类,我觉得对于用于删除特定元素的成员函数可能会导致内存泄漏。代码如下。

struct node
{
    int data;
    node *next;
};

class linked_list
{
private:
    node *head,*tail;
public:
    linked_list()
    {
        head = NULL;
        tail = NULL;
    }
    void add_node(int n)
    {
        node *tmp = new node;
        tmp->data = n;
        tmp->next = NULL;

        if(head == NULL)
        {
            head = tmp;
            tail = tmp;
        }
        else
        {
            tail->next = tmp;
            tail = tail->next;
        }
        
    }
    void DelElem(int locat)
    {
        int j{1};
        node* tmp = new node;     
        if (locat == 1)
        {      
            tmp  = head->next;
            head = tmp;
            delete tmp;
        }
        else
        {
            node* n = head;
            while (j < locat - 1)
            {
                n = n->next;
                j++;
            }
            tmp = n->next;
            n->next = tmp->next;
            delete tmp; 
        } 
    }

对于函数'DelElem',我首先通过 new 运算符创建了一个指针 tmp。但是,我为其分配了不同的地址,这意味着我在初始化时丢失了原始地址。

我该如何解决这个问题?

标签: c++c++11pointersmemory-leaksnew-operator

解决方案


您的代码实例几乎没有问题,我已更正:-

  1. 正如其他人所指出的,您不需要使用 `new` 关键字来声明指针。
  2. 当尝试删除链表的第一个节点时,根据您的代码,它将删除第二个节点,原因如下
    tmp  = head->next;
    head = tmp;
    delete tmp;
    

    这里,tmp最初是指向第二个节点,因为head->next指的是第二个节点。因此,与其相反,它应该是这样的:-

    tmp = head;
    head = head->next;
    delete tmp;
    

    现在,tmp将指向第一个节点,在第二行中,head将指向第二个节点,然后tmp删除指向的第一个节点。

这是代码的更正版本:-

struct node {
    int data;
    node* next;
};

class linked_list {
private:
    node *head, *tail;

public:
    linked_list()
    {
        head = NULL;
        tail = NULL;
    }
    void add_node(int n)
    {
        node* tmp = new node;
        tmp->data = n;
        tmp->next = NULL;

        if (head == NULL) {
            head = tmp;
            tail = tmp;
        }
        else {
            tail->next = tmp;
            tail = tail->next;
        }
    }
    void DelElem(int locat)
    {
        int j{ 1 };
        node* tmp;
        if (locat == 1) {
            tmp = head;
            head = head->next;
            delete tmp;
        }
        else {
            node* n = head;
            while (j < (locat - 1)) {
                n = n->next;
                j++;
            }
            tmp = n->next;
            n->next = tmp->next;
            cout << tmp->data;
            delete tmp;
        }
    }
};

推荐阅读