c++ - 尝试删除链表时出现分段错误
问题描述
我尝试使用动态内存分配创建一个非常基本的链表。您可以添加元素并遍历列表。但是我在编写程序的析构函数时似乎遇到了问题(出现分段错误)。
我取而代之的是从我的析构函数中获取代码,然后将其放入一个名为的成员函数中,该函数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
解决方案
推荐阅读
- reactjs - 为什么副作用在 React 中不行
- c# - .NET Core program.cs 和 Startup.cs 未命中
- python - AssertionError: Padding_idx 必须在 num_embeddings 内
- java - 将分钟添加到对象表示的时间
- java - 将证书添加到 Mirth Keystore
- javascript - 如何检测浏览器视口中的元素?
- css - 如果我直接从谷歌链接图像 url,如何降低背景图像的不透明度?
- python - 如何创建具有两个列表和相同键的字典
- c - 数组循环的错误逻辑在程序运行时给出双重(意外)结果
- javascript - 异步函数在等待后不会触发代码