free():在调用赋值运算符时,在tcache 2中检测到双重free



我刚刚问了一个非常相似的问题,但我已经看过了这个问题的答案,我只是看不出这次我做错了什么。我正在做一个使用链表实现c++list<int>的大学项目。我正在做赋值运算符,以下是我目前掌握的内容。

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

当我运行时,助理操作员确实会将数据从一个列表复制到另一个列表,但我在运行后得到了这个-

free(): double free detected in tcache 2

我不明白我是怎么不恰当地使用指针的。有人能告诉我我做错了什么吗?

编辑:析构函数可能也很有用。

```
Linkedlist::~Linkedlist() {
Node *del;
while(head != NULL)
{
del = head;
head = head -> next;
delete del;
}
}

编辑:很抱歉,我对Stack Overflow很陌生。如果我正确理解MRE,这里是要复制的最小代码量(上面的所有内容,加上我的主程序和构造函数(。

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

调用Linkedlist的构造函数不会崩溃,它只会在我调用赋值时崩溃。我在valgrind中运行了我的程序,但由于我对内存管理还很陌生,我不太确定我在看什么。它在我的析构函数中显示了我和无效的free((,但我找不到它之前已经免费的地方。

行:

Linkedlist b = a;

调用复制构造函数,而不是赋值运算符。如果您没有提供复制构造函数,那么编译器生成的构造函数将只复制head指针。然后,在销毁期间,相同的head将从列表a和列表b中删除,导致";双自由";。

最新更新