以下代码应该从用户输入创建链接列表并显示它,但显示功能会导致分段错误。
#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);
答案 0 :(得分:1)
问题在于以下几行:
struct node* head;
struct node* prev;
struct node temp;
head = &temp;
prev = &temp;
由于temp在堆栈上声明,因此当它超出范围时会丢失 - 在这种情况下,在函数结束之后。由于您将temp的地址分配给head和prev,因此返回的head指向垃圾堆栈。
答案 1 :(得分:0)
而不是
struct node temp;
head = &temp;
prev = &temp;
应该是
head =(struct node *)malloc(sizeof(struct node));
prev = head;
您正在返回存储在堆栈中的本地结构的内存地址。相反,您应该从堆请求内存来存储头节点并将地址返回到该节点。