gpt4 book ai didi

c++ - 我很难修复我认为是双重免费的东西

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:09:13 25 4
gpt4 key购买 nike

我正在尝试创建一个链表 vector 作为类成员。 Valgrind 显示没有内存泄漏,但也会在程序结束时产生 Invalid free()/delete/delete[]/realloc() 错误。

我试图通过为链表编写析构函数、复制构造函数和复制赋值运算符来解决这个问题。我相信这些已经正确实现。我还尝试了各种向成员 vector 添加链表的方法(引用、指针、智能指针),但似乎都无法解决问题。

#include "lists.h"

lists::lists() {

}

void lists::newList() {
int size, value;
cout << "Please specify size of this list" << endl;
cin >> size;
shared_ptr<list> new_list(new list);
//list *new_list = new list();
for (int i = 0; i < size; i++) {
cout << "Enter value for node " << i + 1 << endl;
cin >> value;
new_list->pushBack(value);
}
list_storage.push_back(new_list);
//delete new_list;
}

void lists::deleteList() {

}

void lists::display() {
for (int i = 0; i < list_storage.size(); i++) {
list_storage[i]->display();
}
}

#include "list.h"

list::list() {
head = NULL;
}

list::list(const list& list) {
head = NULL;
node *current = head;
while (current != NULL) {
this->pushBack(current->data);
current = current->next;
}
}

list& list::operator=(const list& rhs) {
list temp(rhs);
swap(temp.head, head);
return *this;
}

list::~list() {
if (head != NULL) {
node *current = head;
while (current != NULL) {
node *next = current->next;
delete current;
current = next;
}
delete head;
}
}

这是 valgrind 的输出:

==15967== Invalid free() / delete / delete[] / realloc()
...
==15967== HEAP SUMMARY:
==15967== in use at exit: 0 bytes in 0 blocks
==15967== total heap usage: 9 allocs, 10 frees, 74,856 bytes allocated
==15967==
==15967== All heap blocks were freed -- no leaks are possible
==15967==
==15967== For counts of detected and suppressed errors, rerun with: -v
==15967== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

最佳答案

看看你的析构函数:

list::~list() {
if (head != NULL) {
node *current = head;
while (current != NULL) {
node *next = current->next;
delete current;
current = next;
}
delete head;
}
}

进入循环,删除current,这是第一次迭代的head。在循环之后再次删除 head -> double free。

关于c++ - 我很难修复我认为是双重免费的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56477059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com