[英]Segmentation fault while doing malloc for a struct pointer
我試着寫基本的鏈表代碼。 我有兩個函數將數據添加到列表的開頭和列表的結尾。 每次在開頭添加數據的功能都很好。
我總是在insert_end
函數中insert_end
分段錯誤。 在對malloc
執行malloc
之后嘗試訪問temp1
指向結構時,我收到錯誤。 但這與我在insert_first
函數中所做的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;
}
}
}
這是有問題的塊。
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.