2013-10-09 31 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,所以返回的头指向垃圾没有堆栈。