Assignment Operator Overload memory leak

This is about linked list. I don't know why I have memory leak on ASSIGNMENT OPERATOR =. Can you just ignore the other and just focus on the ASSIGNMENT OPERATOR =.
ASSUME ALL THE FUNCTION AND VARIABLES HAVE DECLARED AND WORK PROPERLY.
Can someone help me with it ? thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
struct node
{
	double value;
	node* next;
};

/**< Constructor  */
linkedlist::linkedlist()
{
    head = tail =  NULL;
}

/**< desconstructor   */
linkedlist::~linkedlist()
{
    node * tmp = head;

    while (tmp != NULL)
    {
        node * del = tmp;
        tmp = tmp->next;
        delete del;
    }
    head = tail = NULL;
}

/**< Assignment = */
linkedlist& linkedlist::operator=(const linkedlist& assign)
{
    head = NULL;
    node *tmp;
    tmp = assign.head;

    while (tmp->next != NULL)       //Point to next link not NULL
    {
        add_back(tmp->value);       //keeping adding link list
        tmp = tmp->next;            //move to the next element
    }

    add_back(tmp->value);           //add the last element
    return *this;
}
ASSUME ALL THE FUNCTION AND VARIABLES HAVE DECLARED AND WORK PROPERLY.

That's probably a very bad assumption to make, but whatever.

Look at the first line in your operator=, I suspect that is a big part of the problem.
Last edited on
Sorry for the mess. everything works ok. But when I check cppcheck. it show my operator = has memory leak. Im thinking should i set something to NULL or delete something in there.
Without seeing what and where head is defined, I lean to the idea that setting it to NULL in that first line is where the leak is occurring.

It looks to me like you're leaking the previous contents of the list.

Also, I suspect you aren't handling the case where assign is an empty list.
Thanks all Guy!
Topic archived. No new replies allowed.