class 析构函数分段错误

class destructor segmentation fault

为什么这段代码会导致段错误? 它会导致析构函数中出现段错误。 但是当我在没有析构函数的情况下调用自由函数时,就可以了。 有些回答看不懂问题。 问题是如果我在 main() 中使用自由函数 s.free(); 它工作正常.. 但是我让析构函数做 free() 工作,这不行。

#include<iostream>
using namespace std;

class Stack
{
public:
    int pop() {
        data = next->data;
        auto tmp = next;
        next = next->next;
        delete tmp;
        return data;
    }
    void push(int n) {
        Stack* p = new Stack();
        p->data = n;
        p->next = next;
        next = p;
        size++;
    }
    virtual ~Stack() {
        free();
    }
    void free() {
        while(next) pop();
    }
    Stack* next = nullptr;

protected:
    int data;
    int size = 0;
};
int main()
{
    Stack s;
    for(int i=0; i<30; i++) s.push(i);
}

在class的构造函数中必须设置next = nullptr,否则free()函数中的循环不会停止。 编辑: 我认为问题是因为在你删除的弹出窗口上,它再次调用了析构函数。 试试这个: `

int pop() {
    data = next->data;
    auto tmp = next;
    next = next->next;
    tmp->next = nullptr;
    delete tmp;
    return data;
}

`

您的 pop 函数会破坏整个堆栈。它 deletes tmp 节点(通过调用 Stack 析构函数),它仍然指向新的 next。 由于 Stack 析构函数在 next 上调用 delete,您会在同一对象上看到多个析构函数调用的混乱局面。

JMA 比我快了几秒钟,所以请参考他们的代码修复以获得快速解决方案。

但是,我建议您添加专用的 Node 结构而不是组合 Stacks,这实际上会增加代码的清晰度。