2017-09-28 1 views
0

C++에서 어떻게 링크 된 목록이 작동하는지 이해할 수있는 코드를 만들었고 프로그램이 종료되기 전에 "0이 아닌 상태에서 종료되었습니다"라는 오류 메시지가 나타납니다. 현재 온라인 컴파일러 repl.it C++ 코드를 테스트하는 데 사용하고,이 문제가 관련되어 있는지 잘 모르겠습니다. 어떻게 고칠 수 있니? 여기 내 코드가있다. 세부 세부 세부 세부 세부 세부 세부 사항 detailsdetails detailsdetails detailsdetails detailsdetails 세부 세부0이 아닌 상태 (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; 
} 

출력이 시간 t에서

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 
+2

이 * 주문 확인 (당신은 할 수 없지만 어쩌면 온라인 컴파일러) 디버거를 사용할 수 있습니다. 거기에 초기화되지 않은 포인터를 역 참조하십시오. 장래에 이러한 문제를 발견하려면 먼저 디버거를 사용하십시오. –

+0

당신의 문제에 상관없이'new'를 그렇게 자유롭게 사용하지 마십시오. 'new '를 사용할 때마다 항상'delete'해야하는 메모리를 동적으로 할당합니다. 범위를 벗어날 때'node'를 자동으로 삭제하는 wrapper 클래스 인'unique_ptr '를 사용하거나 내부적으로'new'를 사용하는'add_next' 메소드를'node' 클래스에주고'~ node'를 만드십시오 do do' 다음을 삭제하십시오. 후자의 경우에는 예외 안전 코드를 작성하는 데주의해야합니다. 따라서 'unique_ptr'솔루션을 선호해야합니다. – patatahooligan

+0

'n'행에't'를 일관되게 인쇄하고 있습니다. 복사 및 붙여 넣기가 너무 많습니까? – molbdnilo

답변

1
n=new node; 
    t=t->next; <- error there 
    n->data=4; 
    t->next=n; 
    n->next=NULL; 

사용자가 만든 3 노드이며,이 시간이 노드에있다 next 속성 값이 없습니다. GDB가 더 쉽게 이런 종류의 문제를 볼로

당신은 "4 통과"에있는 당신이 일을 할 *

+0

의미가 있습니다. 고마워요! – user136128

관련 문제