【发布时间】:2013-10-09 20:33:43
【问题描述】:
下面的代码应该是根据用户输入创建一个链表并显示它,但是显示函数会导致分段错误。
#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);
【问题讨论】:
-
调试器说了什么?
-
您正在返回
createLinkedList中的局部变量的地址 -
非常感谢 :) @Andreas
-
谁能推荐一本关于堆和栈内存分配的好书?
标签: c pointers linked-list segmentation-fault