[英]Memory issues with linked list's constructor, destructor and copy constructor
[英]Copy constructor for a linked list leads to a memory error
我正在編寫自己的鏈表類(用於教育目的),這里是:
我的代碼
#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
錯誤: error for object 0x7fff5b8beb80: pointer being freed was not allocated
我不明白為什么。 除了復制構造函數之外,我的邏輯很簡單:我遍歷要復制的列表,即obj
,然后this
列表添加一個新元素,即我要復制到的列表。 由於我add()
函數創建一個,以及一個新的元素, new
,我不能看到我的兩個列表分享這我想在析構函數刪除兩次的元素。 我究竟做錯了什么?
您忘記在復制構造函數中初始化您的_head
:
// Copy constructor
LinkedList(const LinkedList &obj) {
_head = NULL; // <- Add This
ListNode *node = obj._head;
while (node != nullptr) {
this -> add(node -> val);
node = node -> next;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.