I've just asked a very similar question, but I've been over the answers to that one and I just can't see what I'm doing wrong this time around. I'm working on a university project implementing the c++ list<int>
using a linked list. I'm working on the assignment operator, and here's what I have so far.
Linkedlist &Linkedlist::operator=(const Linkedlist &l) {
clear();
if(l.empty())
{
return *this;
}
Node *iterRight = l.head;
head = new Node;
Node *iterLeft = head;
while(iterRight != NULL)
{
iterLeft -> data = iterRight -> data;
iterLeft -> next = new Node;
iterLeft -> next -> prev = iterLeft;
iterLeft = iterLeft -> next;
iterRight = iterRight -> next;
}
return *this;
}
When I run, the assingment operator DOES work to copy the data from one list to another, but I get this after the run -
free(): double free detected in tcache 2
I don't understand how I used my pointers inappropriately. Can someone show me what I'm doing wrong?
EDIT: The destructor might be useful too.
```
Linkedlist::~Linkedlist() {
Node *del;
while(head != NULL)
{
del = head;
head = head -> next;
delete del;
}
}
EDIT: My apologies, I'm very new to Stack Overflow. If I understand a MRE correctly, here's the minimum amount of code to reproduce (Everything above with the addition of my main program and my constructor).
int main() {
Linkedlist a(20);
Linkedlist b = a;
return 0;
}
Linkedlist::Linkedlist(unsigned int n) {
size = n;
tail = NULL;
head = new Node;
Node *iter = head;
for(int i = 0; i < n; i++)
{
iter -> data = i;
iter -> next = new Node;
iter -> next -> prev = iter;
iter = iter -> next;
}
tail = iter -> prev;
tail -> next = NULL;
}
Calling the constructor for the Linkedlist a does not crash, it only crashes once I call the assignment. I ran my program in valgrind, but since I'm rather new at memory management, I'm not quite sure what I'm looking at. It shows me and invalid free() in my destructor, but I can't find where it was already free'd prior.
The line:
Linkedlist b = a;
calls copy constructor, not assignment operator. If you didn't provide copy constructor, then the compiler-generated one will just copy head
pointer. Then, during destruction the same head
will be deleted both from list a
and list b
leading to "double free".