我尝试编写基本的链表代码。我有两个函数将数据添加到列表的开头和列表的结尾。每次在开头添加数据的功能都可以正常工作。
我总是在insert_end
函数中遇到分段错误。
在对temp1
执行malloc
之后尝试访问insert_first
指针时,我收到错误。但这与我在struct node *temp1,*trav;
temp1 = (struct node *)malloc(sizeof(struct node));
trav = (struct node *)malloc(sizeof(struct node));
if (temp1 != NULL) { //******************Segmentation fault at this line**********
temp1->data = input;
}
#include<stdio.h>
#include<stdlib.h>
//*******Structure to hold linked list*********//
struct node {
int data;
struct node *next;
}*head,*temp;
//***********Function to Display everything**********//
void display(struct node *head) {
struct node *trav;
trav= (struct node *)malloc(sizeof(struct node));
printf("Entering into Display\n");
if (head == NULL) {
printf("Oh My God, the list is empty\n");
}
else {
trav = head;
while (trav != NULL) {
printf("Value stored in [%p] is [%d]\n",trav,trav->data);
trav = trav->next;
}
}
}
//***********Function to Insert at beginning*********//
struct node *insert_first(struct node *head,int input) {
temp = (struct node *)malloc(sizeof(struct node));
temp->data = input;
printf("\nEntering insert first");
if (head == NULL) {
head = temp;
head->next = NULL;
}
else {
temp->next = head;
head = temp;
}
return head;
}
//**************Function to Insert at End******************//
struct node *insert_last(struct node *head,int input) {
struct node *temp1,*trav;
temp1 = (struct node *)malloc(sizeof(struct node));
trav = (struct node *)malloc(sizeof(struct node));
if (temp1 != NULL) {
temp1->data = input;
}
else {
printf("empty");
}
printf("\nEntering insert last");
if (head == NULL) {
head = temp1;
head->next = NULL;
}
else {
trav = head;
while (trav != NULL) {
trav = trav->next;
}
trav->next = temp1;
}
return head;
}
//*************Main Fucntion***********//
int main() {
int choice,value;
head = NULL;
while(1) {
printf("\n******Please Enter your choice****\n1. To insert at beginning\n2. To insert at End\n3. To Insert middle\n4. To delete\n5. To display\n0. To Exit\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Please Enter the value to be added\n");
scanf("%d",&value);
head = insert_first(head,value);
break;
case 2:
printf("Please Enter the value to be added\n");
scanf("%d",&value);
head = insert_last(head,value);
break;
case 5:
display(head);
break;
case 0:
return 0;
default:
printf("Thats a wrong choice\n");
break;
}
}
}
函数中所做的事情完全相同,但每次都有效。我试着谷歌搜索并在论坛中尝试,没有答案。请帮忙。
此链接是我确切的问题..但我完全不了解解决方案
Segmentation fault in C with malloc
我在这个块上特别容易出错
{{1}}
答案 0 :(得分:3)
这是一个有问题的障碍。
else {
trav = head;
while (trav != NULL) {
trav = trav->next;
}
trav->next = temp1;
当您离开while循环时,trav
为NULL
。这就行了
trav->next = temp1;
因违反分段而失败。
将该块更改为:
else {
trav = head;
while (trav->next != NULL) {
trav = trav->next;
}
trav->next = temp1;