【发布时间】:2017-09-28 12:46:14
【问题描述】:
我编写了一些代码来了解链表在 C++ 中是如何工作的,并且在程序终止之前它会显示错误“以非零状态退出”。我目前正在使用在线编译器 repl.it 来测试 C++ 代码,我不确定这个问题是否相关。我如何解决它?这是我的代码。详情详情详情详情详情详情详情详情详情详情详情详情详情详情详情详情
#include <iostream>
#include <string>
using namespace std;
struct node{
int data;
node* next;
};
int main()
{
node* n; //new
node* t; //temp
node* h; //header
n=new node;
n->data=1;
t=n;
h=n;
cout <<"Pass 1"<<endl;
cout <<"t=" << t << endl;
cout <<"n=" << t << endl;
cout <<"h=" << h << endl;
cout << n->data << endl;
n=new node;
n->data=2;
t->next=n;
t=t->next;
cout <<"Pass 2"<<endl;
cout <<"t=" << t << endl;
cout <<"n=" << t << endl;
cout <<"h=" << h << endl;
cout << n->data << endl;
n=new node;
n->data=3;
t->next=n;
t=t->next;
cout <<"Pass 3"<<endl;
cout <<"t=" << t << endl;
cout <<"n=" << t << endl;
cout <<"h=" << h << endl;
cout << n->data << endl;
//Test pass
//exits with non-zero status
//NULL to pointer means invalid address; termination of program?
n=new node;
t=t->next;
n->data=4;
t->next=n;
n->next=NULL;
cout <<"Pass 4"<<endl;
cout <<"t=" << t << endl;
cout <<"n=" << t << endl;
cout <<"h=" << h << endl;
string a;
a="End test";
cout << a << endl;
return 0;
}
输出是
Pass 1
t=0x12efc20
n=0x12efc20
h=0x12efc20
1
Pass 2
t=0x12f0050
n=0x12f0050
h=0x12efc20
2
Pass 3
t=0x12f0070
n=0x12f0070
h=0x12efc20
3
exited with non-zero status
【问题讨论】:
-
检查您在“第 4 步”中执行操作的顺序。您在那里取消引用未初始化的指针。以后请先使用调试器找出此类问题。
-
不管你有什么问题,不要这么随意地使用
new。每次您在超出范围时使用new, you dynamically allocate memory that you always have todelete. Either useunique_ptr, a wrapper class that automatically deletes thenode`,或者给您的node类一个add_next内部使用new的方法并生成~node做delete next。在后一种情况下,您必须小心编写异常安全代码,这就是为什么您应该更喜欢unique_ptr解决方案。 -
您始终在
n=行上打印t。复制粘贴太多? -
不幸的是它是一个在线编译器,所以它没有调试器。下次我会使用那个包装类,谢谢。是的,它应该是 n,但在这种情况下它恰好也等于 t。