【问题标题】:Exited with non-zero status (repl.it) C++?以非零状态 (repl.it) C++ 退出?
【发布时间】: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 to delete. Either use unique_ptr, a wrapper class that automatically deletes the node`,或者给您的node 类一个add_next 内部使用new 的方法并生成~nodedelete next。在后一种情况下,您必须小心编写异常安全代码,这就是为什么您应该更喜欢unique_ptr 解决方案。
  • 您始终在 n= 行上打印 t。复制粘贴太多?
  • 不幸的是它是一个在线编译器,所以它没有调试器。下次我会使用那个包装类,谢谢。是的,它应该是 n,但在这种情况下它恰好也等于 t。

标签: c++ status


【解决方案1】:
  n=new node;
  t=t->next;  <- error there
  n->data=4;
  t->next=n;
  n->next=NULL;

此时t 是您创建的第三个节点,此时此节点没有值是next 属性。

您可以使用调试器作为 gdb 来更轻松地查看此类问题(但可能在您的在线编译器中您不能)

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 2022-06-21
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 2017-05-18
    • 2013-12-23
    • 1970-01-01
    相关资源
    最近更新 更多