删除指针后出现分段错误(核心转储)
Segmentation errors(core dumped) after deleting pointers
我正在尝试制作一个口罩交付、订购服务代码。函数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
以避免满足这个"条件";如果";再一次
相关文章:
- 如何找出GDB的SIGTRAP核心转储的根本原因
- C++映射分割错误(核心转储)
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 浮点异常(核心转储)#694457
- 分段错误(核心转储)但无法弄清楚
- 链接到libkcapi时没有核心转储
- 分段错误(核心转储) - 使用 SavedModel 的 Tensorflow C++ API 进行推断
- 在基数排序中,我得到 munmap_chunk():无效指针和中止(核心转储).为什么?
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 合并排序:分段错误核心转储
- C++:分段错误(核心转储)
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- 如何使用 lldb 在曼扎罗中调试 lz4 文件格式的核心转储?
- qt C++命令行代码中的分段错误(核心转储)
- 从文件中读取的数据,但发生核心转储错误
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- C++ atof - 分段错误(核心转储)
- Linux C 只禁止我的程序使用核心转储
- 为什么我的代码包含错误分段错误(核心转储)?