2017-07-20 63 views
-1
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时开始发生。运行时malloc:***错误,只发生有时

#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; 
} 
+2

不要将堆栈溢出与调试器混淆。如果你知道去哪里看,那些会给你详细的报告。 – tadman

+0

我明白你在说什么,但是我已经尝试了几个小时的问题,但没有运气。正如你可以从代码中明显地看出这是家庭作业,而且这个错误阻止了我能够完成即将到期的更大的任务的其余部分。作为初学者,我只是希望有人能够帮助我克服这个令人沮丧的障碍,所以我可以继续使用我的其他代码。 – NickR

+0

@NickR,在linux下有内存调试器:Valgrind。尝试使用'valgrind。/ your_program',它会检测到许多内存管理错误。或者在你的情况下,尝试在你分配内存并释放内存的所有地方添加调试'fprintf'到'stderr'(或'<<'-ing到'std :: cerr')。你不能在没有新增的东西上调用delete。 – osgx

回答

-1

错误是字面上告诉你,pointer being freed was not allocated。在C++中释放指针意味着您正在使用指针上的delete运算符。这应该会帮助你,而不会给你答案。

尝试并自己解决这些问题,尤其是在做家庭作业时。如果你有人为你解决你的问题,你不会知道。

考虑通过smart pointers进行自动内存管理。

祝你好运。

相关问题