mardi 16 février 2021

C++: potential memory leak in linked list

I'm writing a class of linked list, I feel that for the member function that used to delete specific element might cause the memory leak. The code is below.

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; 
        } 
    }

For function 'DelElem', I firstly created a pointer tmp by new operator. However, I assign different address for it which means I lost the original one at the initialization.

How can I fix this problem?

Aucun commentaire:

Enregistrer un commentaire