首页 > 解决方案 > 尝试删除链表时出现分段错误

问题描述

我尝试使用动态内存分配创建一个非常基本的链表。您可以添加元素并遍历列表。但是我在编写程序的析构函数时似乎遇到了问题(出现分段错误)。

我取而代之的是从我的析构函数中获取代码,然后将其放入一个名为的成员函数中,该函数purge()没有产生任何错误。这是为什么呢?我的课有什么根本性的问题吗?

  #include <iostream>
struct LList
{
    LList *p , *s;
    int data;
    LList (LList *prev , LList *succ, int n) : p{prev} , s{succ} , data{n}{}
    ~LList()
    {

        auto start = this;
        while (start->p ) start = start->p;
        while(1)
        {
            auto temp = start;
            start = start->s;
            delete temp;
            if (start == nullptr) break;
        }
        std::cout << "Destruted!";
    }
    void traverse() const
    {
        auto start = this;
        while (start->p != nullptr)start = start->p;
        while (1)
        {
        std::cout << start->data;
        if (start->s == nullptr) break;
        else start = start->s;
        }
    }
};
int main()
{
    LList *natural = new LList{nullptr , nullptr , 1};
    natural = new LList{natural, nullptr , 2};
    natural->p->s = natural;
    natural = new LList{natural, nullptr , 5};
    natural->p->s = natural;
    natural->traverse();
    std::cout << natural->data;
    natural->~LList();
}

带清洗的版本:

#include <iostream>
struct LList
{
   ....
    void purge()
    {

        auto start = this;
        while (start->p ) start = start->p;
        while(1)
        {
            auto temp = start;
            start = start->s;
            delete temp;
            if (start == nullptr) break;
        }
        std::cout << "Destruted!";
    }
    void traverse() const
    {
        auto start = this;
....
int main()
{
    ...
    natural->purge();
}

ps:即使清洗也能解决问题吗?我还可以去:

natural->purge();
    std::cout << natural->data;
}

接近尾声,它会输出125Disrupted!5

标签: c++linked-list

解决方案


推荐阅读