【发布时间】:2020-03-12 11:17:24
【问题描述】:
我正在编写自己的链表类(用于教育目的),它是:
我的代码
#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 创建了一个新元素,因此我看不到我的两个列表在哪里共享一个我试图在析构函数中删除两次的元素。我究竟做错了什么?
【问题讨论】:
-
代码对我来说看起来不错。您可以使用调试器查看错误来自哪一行代码吗? (在Linux上,运行程序时将
gdb放在程序前面,当它打印错误并暂停时,键入bt以查看调用堆栈) -
您的代码在 VS2017 中运行良好,没问题,我可以毫无问题地运行它。尝试清理解决方案并重建它并检查。
-
到目前为止代码对我来说看起来不错,你确定你运行的代码就是你编译的代码吗?否则使用你的调试器。如果你不知道如何使用它,是时候开始学习了。
-
@user253751 我在 Mac OS X 上使用 CLion。我问了一个也使用 CLion + Mac OS X 的朋友(不过她的操作系统版本较新),她说她遇到了同样的错误。
-
不是这个程序的问题,但不要忘记三法则:给
LinkedList和operator=(const LinkedList&)。然后,您可以选择遵循五规则来改进课程。
标签: c++ pointers linked-list copy-constructor