编码SLL时获取中止陷阱6

时间:2018-03-04 14:51:48

标签: c++ linked-list singly-linked-list

我是c ++的新手。试图制作一个简单的单链表程序。代码如下。在这里,我创建了一个Node类,SLL类和相应的函数。

#include <iostream>
using namespace std;
class Node{

    private:
        int data;
        Node* next;

    friend class SLL;
};

class SLL{
    public:
        SLL();
        ~SLL();
        bool empty() const;
        const int& front() const;
        void addFront(const int& e);
        void removeFront();
        void printList();
    private:
        Node* head;
};

SLL::SLL()
    :head(NULL){ }

SLL::~SLL(){
    while(!empty())
        removeFront();
}

bool SLL::empty() const{
    return head == NULL;
}
void SLL::removeFront(){
    Node* temp = head;
    head = temp->next;
    delete temp;
}

void SLL::addFront(const int& e){
    Node* n = new Node;
    n->data = e;
    n->next = head;
    head = n;
}

void SLL::printList(){
    Node* temp = head;
    // int n =0 ;
    while(temp->next){
        // n++;
        cout<< temp->data << " ";
        temp = temp->next;
    }
    delete temp;
}

int main(){
    SLL a;
    a.addFront(1); 
    a.printList();
}

编译程序时,出现以下错误。

ol(36664,0x7fff8a6e0340) malloc: *** error for object 0x7fb055402820: pointer being freedwas not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

为什么会出现此错误?什么是解决方案呢?

1 个答案:

答案 0 :(得分:2)

delete temp;中的printList不会破坏变量 temp;局部变量已经自动销毁。 (实际上,技术术语是“自动存储持续时间”。)毕竟,

中不需要(或可能)delete
void f() {
  int i=std::rand();
  std::cout << i;
}

它会破坏对象 temp点,从而破坏您的列表。

delete只使用一次new:在这种情况下,这意味着要平衡addFrontremoveFront(这应该具有直观意义),包括在析构函数中 - 你已经在做什么了。