Assignment Operator Overload memory leak
Nov 18, 2014 at 6:20pm UTC
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 ;
}
Nov 18, 2014 at 6:43pm UTC
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 Nov 18, 2014 at 6:44pm UTC
Nov 18, 2014 at 9:03pm UTC
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.
Nov 18, 2014 at 9:11pm UTC
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.
Nov 18, 2014 at 9:29pm UTC
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.
Nov 18, 2014 at 9:48pm UTC
Thanks all Guy!
Topic archived. No new replies allowed.