删除指针后出现分段错误(核心转储)

Segmentation errors(core dumped) after deleting pointers

本文关键字:核心 转储 错误 分段 指针 删除      更新时间:2024-09-24

我正在尝试制作一个口罩交付、订购服务代码。函数order将向订单列表中添加一个新订单。函数output将按最新到最旧的顺序输出列表。函数deliver删除最旧的顺序。以下是代码:

#include <iostream>
#include <string>
using namespace std;
struct Mask {
string type;
string customer;
Mask *next;
};
void order(Mask *&head, string type, string customer){
cout << "Ordering " << type << " for " << customer << endl;
Mask *oldHead = head;
head = new Mask;
head->type = type;
head->customer = customer;
head->next = oldHead;
}
void output(Mask *head){
cout << "Outputting order list " << endl;
for (Mask *p = head; p != NULL; p = p->next)
cout << "  " << p->type << " for " << p->customer << endl;
}
void deliver(Mask *&head){
if (head->next == NULL){
cout << "Delivering " << head->type;
cout << " for " << head->customer << endl;
delete head;
}
else
deliver(head->next);
}
int main()
{
Mask *head = NULL;
order(head, "3M-N95", "Alice");
order(head, "OxyAir", "Burce");
order(head, "3M-N95", "Cindy");
output(head);
deliver(head);
output(head);
}

一切都运行得很顺利,但它最后说分割错误(核心转储(。我试着添加这个:

if (head->next->next == NULL){
deliver(head->next);
head->next == NULL;
}

但问题仍然存在。感谢您的帮助。

我将deliver更改为:

void deliver(Mask *&head){
if (head->next->next == NULL){
cout << "Delivering " << head->next->type;
cout << " for " << head->next->customer << endl;
head->next = head->next->next;
delete head->next;
}
else
deliver(head->next);
}

显然,仅仅将指针设置为NULL并不能解决问题,所以我只是更新了它,使倒数第二个指针直接指向末尾。

在"交付";强制函数满足条件if(head->next == NULL)然后尝试到达CCD_ 6,这就像尝试说空->下一个(导致分割错误(。我建议遍历到最后一个";掩码";对象,而不是使用所有那些"while"循环;如果";导致相同结果的语句,或者至少将第二个if更改为else if以避免满足这个"条件";如果";再一次