2012-05-07 13 views
0

このプログラムはリンクリストを作成します。 このプログラムを実行すると、セグメンテーションフォールトが発生します。リンクリストプログラムのセグメント化エラー

#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; 
} 

エラーとは? これは私があなたは、その最初の宣言と初期化後rootに何かを割り当てることはありませんので、それは常にNULLあり、そしてあなたがtravel()でデリファレンスに進み

[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'sを使用してください。 – Mat

答えて

3

を実行する方法です。

struct node *t1; 
t1=root; 

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

そのバグを修正してpushを呼び出すと、まったく同じバグに悩まされます。 –

関連する問題