c++ - 链表的复制构造函数导致内存错误
问题描述
我正在编写自己的链表类(出于教育目的),它是:
我的代码
#include <iostream>
using namespace std;
#define PRINT(x) #x << " = " << x << " "
struct ListNode {
int val;
ListNode* next = nullptr;
ListNode(int x) : val(x), next(nullptr) {}
};
class LinkedList {
private:
ListNode* _head;
unsigned long long int _size;
public:
LinkedList() :_head(nullptr), _size(0) {}
LinkedList(ListNode* _h) :_head(_h), _size(0) {
ListNode* node = _head;
while (node != nullptr) {
_size++;
node = node->next;
}
}
// Copy constructor
LinkedList(const LinkedList& obj) {
ListNode* node = obj._head;
while (node != nullptr) {
this->add(node->val);
node = node->next;
}
}
~LinkedList() {
while (_head != nullptr) {
remove();
}
}
void add(const int& value) {
ListNode* node = new ListNode(value);
node->next = _head;
_head = node;
_size++;
}
int remove() {
int v = _head->val;
ListNode* node = _head;
_head = _head->next;
delete node;
_size--;
return v;
}
void print() {
if (size() == 0) {
cout << "List is empty" << endl;
return;
}
ListNode* node = _head;
while (node->next != nullptr) {
cout << node->val << " -> ";
node = node->next;
}
cout << node->val << endl;
}
unsigned long long int size() { return _size; }
ListNode* head() { return _head; }
};
int main() {
LinkedList L;
L.add(4);
L.add(3);
L.add(2);
L.add(1);
L.print();
LinkedList L2(L);
return 0;
}
问题是当我运行这段代码时,我得到这个错误:error for object 0x7fff5b8beb80: pointer being freed was not allocated
我不明白为什么。我在复制构造函数之外的逻辑很简单:我遍历我正在复制的列表,即obj
,并向列表添加一个新元素this
,也就是我要复制到的列表。由于我的add()
函数创建了一个新元素,好吧,new
我看不到我的两个列表在哪里共享一个我试图在析构函数中删除两次的元素。我究竟做错了什么?
解决方案
您忘记初始化_head
in 复制构造函数:
// Copy constructor
LinkedList(const LinkedList &obj) {
_head = NULL; // <- Add This
ListNode *node = obj._head;
while (node != nullptr) {
this -> add(node -> val);
node = node -> next;
}
}
推荐阅读
- automated-tests - 如何在运行工作者中重试失败的步骤?
- python - 在 Python 中与 Clips 规则引擎进行通信
- python - 对于 1 个字典中的每个值获取键,对于 2 个字典中的那些键,打印所有特定键对的值差异
- json - json响应spring boot中缺少字段
- android - MPAndroidChart - MarkerView 不显示阴影
- python - 如何编写 pymongo 查询以获取基于日期时间 Python 的所有数据
- r - 使用 R 的指标函数捕获范围
- c# - GetDirectoryContents 方法不显示超过 28MB 的文件
- java - 如何在给定端点和中点的情况下找到另一个端点
- javascript - JS:无法读取未定义的属性“排序” - 定义类函数的参数