编码SLL时获取中止陷阱6

问题描述 投票:-1回答:1

我是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

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

c++ linked-list singly-linked-list
1个回答
2
投票

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

void f() {
  int i=std::rand();
  std::cout << i;
}

它破坏了temp指向的对象,从而破坏了你的清单。

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

© www.soinside.com 2019 - 2024. All rights reserved.