Homework 2(11785,0x100082000) malloc: *** error for object
enter code here0x73203a296b636f6c: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
d c b a (lldb)
如果我在调试器中单步执行我的代码,则不会发生此错误,但不这样做,让我很难找到问题的根源。它也不会在每次运行程序时发生,但有时甚至在我根本不更改代码时也会发生。它也只在我在main中调用赋值运算符时开始出现,b = a。
#include <iostream>
#include <string>
using namespace std;
typedef string ItemType;
class LinkedList {
private:
struct Node {
ItemType value;
Node *next;
};
Node *head;
int m_size;
public:
// default constructor
LinkedList() : head(nullptr) {
m_size = 0;
}
// copy constructor
LinkedList(const LinkedList& rhs){
head = nullptr;
Node *p = nullptr;
for (Node* n = rhs.head; n != nullptr; n = n->next)
{
Node* newNode = new Node;
newNode->value = n->value;
if (p != nullptr)
p->next = newNode;
if (head == nullptr)
head = newNode;
p = newNode;
}
m_size = rhs.m_size;
}
// Destroys all the dynamically allocated memory
// in the list.
~LinkedList(){
Node* n = head;
Node* prev = nullptr;
while (n != nullptr) {
prev = n;
n = n->next;
delete prev;
}
}
// assignment operator
const LinkedList& operator=(const LinkedList& rhs){
LinkedList *copy = new LinkedList (rhs);
head = copy->head;
m_size = copy->m_size;
return *this;
}
// Inserts val at the front of the list
void insertToFront(const ItemType &val){
Node* currentHead = head;
head = new Node;
head->value = val;
head->next = currentHead;
m_size++;
}
// Prints the LinkedList
void printList() const{
Node* n = head;
while (n != nullptr)
{
cout << n->value;
n = n->next;
}
}
int main(){
LinkedList a;
a.insertToFront(" a ");
a.insertToFront(" b ");
a.insertToFront(" c ");
a.insertToFront(" d ");
a.printList();
LinkedList b;
b = a;
return 0;
}
答案 0 :(得分:-1)
该错误实际上是在告诉您pointer being freed was not allocated
。在C ++中释放指针意味着您在指针上使用delete
运算符。这应该可以帮助你,而不会给你答案。
自己尝试并解决这些问题,特别是当它是家庭作业时。如果有人为您解决问题,您将无法学习。
通过smart pointers考虑自动内存管理。
祝你好运。