2012-05-07 4 views
0

이 프로그램은 링크 목록을 작성합니다. 이 프로그램을 실행하면 세그먼트 오류가 발생합니다.linklist 프로그램의 세그먼트 오류

#include <stdio.h> 
#include <stdlib.h> 
struct node { 
    int data; 
    struct node *next, *prev; 
}; 
struct node *root=NULL; 
void push (int); 
void pop (void); 
struct node * create_node (int); 
void travel (void); 
int main() 
{ 
    int i, j, choice, count; 
    printf("enter choice\n"); 
    scanf("%d", &choice); 
    count = 0; 
    while (choice == 1) { 
     printf("enter a data element"); 
     scanf("%d", &j); 
     count++; 
     printf("enter choice\n"); 
     scanf("%d", &choice); 
    } 
    printf("the link list is \n"); 
//travel function to be created 
    travel(); 
} 

void push(int data) 
{ 
    struct node *t1; 
    t1=root; 
    while(t1->next!=NULL) 
    { 
    t1=t1->next; 
    } 
    t1->next=create_node(data); 
} 

void pop() 
{ 
} 


void travel (void) 
{ 
    struct node *t1; 
    t1=root; 
    while (t1->next!=NULL) 
    { 
     printf("%d ",t1->data); 
    } 
    printf("%d ",t1->data); 
} 
struct node * create_node (int data) 
{ 
    struct node *p = (struct node *) malloc (sizeof(struct node)); 
    p->data=data; 
    p->next=NULL; 
    p->prev=NULL; 
    return p; 
} 

어떤 오류가있을 수 있습니까? 이 내가

[email protected]:~/programming$ ./a.out 
enter choice 
1 
enter a data element45 
enter choice 
1 
enter a data element67 
enter choice 
1 
enter a data element89 
enter choice 
0 
the link list is 
Segmentation fault 
+2

[스택 오버플로는 개인 연구 지원자가 아닙니다.] (http://meta.stackexchange.com/a/128553/158667) 디버거 또는 printf를 사용하여 문제의 범위를 좁혀주십시오. – Mat

답변

3

당신은 그것의 초기 선언과 초기화 후 root에 아무것도 지정하지 실행 방법, 그래서 항상 NULL, 당신은 travel()에서 역 참조를 진행합니다.

struct node *t1; 
t1=root; 

// what if root is NULL? Too late... segfault (you hope) 
while(t1->next!=NULL) 
+0

그리고 그 버그를 수정하고 푸시 호출을 시작하면 똑같은 버그로 고생하게 될 것입니다. –