2013-10-09 30 views
0

下面的代碼應該從用戶輸入創建一個鏈接列表並顯示它,但顯示函數會導致段錯誤。打印鏈表會導致C程序中的段錯誤

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
#include<malloc.h> 

struct node{ 
    int value; 
    struct node *next; 
}; 

struct node* createLinkedList() 
{ 
    char string[6]; 
    char string2[6] = "exit"; 
    struct node* head; 
    struct node* prev; 
    struct node temp; 
    head = &temp; 
    prev = &temp; 
    prev->next = NULL; 
    printf("Enter the first number\n"); 
    scanf("%s",string); 
    if(strcmp(string,string2)!=0){ 
    prev->value=atoi(string); 
    } 
    while(strcmp(string,string2)!=0){ 
    printf("Enter the next number\n"); 
    scanf("%s",string); 
    if(strcmp(string,string2)!=0){ 
     prev->next=(struct node *)malloc(sizeof(struct node)); 
     prev->next->next=NULL; 
     prev->next->value=atoi(string);  
     prev = prev->next; 
    } 
    else{ 
     break; 
    } 
    } 
    return head; 
} 

void printLinkedList(struct node* head){ 
    struct node* current = head; 
    while(current!=NULL){ 
    printf("%d -> ",current->value); 
    current=current->next; 
    } 
} 

int main() 
{ 
    struct node *first; 
    first = createLinkedList(); 
    printLinkedList(first); 
    return(0); 
} 

這裏是調試信息:

Enter the first number 
1 
Enter the next number 
2 
Enter the next number 
3 
Enter the next number 
4 
Enter the next number 
exit 

Program received signal SIGSEGV, Segmentation fault. 
0x0000000000400865 in printLinkedList (head=0x7fffffffe150) at linkedList.c:45 
45  printf("%d -> ",current->value); 
+1

調試器說了什麼? – pm100

+5

您正在'createLinkedList' –

+0

中返回一個局部變量的地址,謝謝很多人:) @Andreas – user2086905

回答

0

struct node temp; 
head = &temp; 
prev = &temp; 

相反,它應該是

head =(struct node *)malloc(sizeof(struct node)); 
prev = head; 

您正在返回本地結構的內存地址,該地址存儲在堆棧上。相反,你應該從堆請求內存來存儲頭節點並返回地址。

1

問題出在下面幾行:

struct node* head; 
struct node* prev; 
struct node temp; 
head = &temp; 
prev = &temp; 

由於臨時被堆疊時,超出範圍則失去了聲明 - 該功能結束後,在這種情況下。由於您將temp的地址分配給head和prev,所以返回的頭指向垃圾沒有堆棧。