简体   繁体   中英

Printing a linked-list causes segmentation fault in C program

The following code is supposed to create a linked list from user input and display it, but the display function causes a segmentation fault.

#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);
}

Here is the debug info:

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);

The problem lies in the following lines:

struct node* head;
struct node* prev;
struct node temp;
head = &temp;
prev = &temp;

Since temp is declared on the stack it is lost when it goes out of scope - in this case after the end of the function. Since you assign the address of temp to both head and prev, the returned head points to garbage no the stack.

Instead of

struct node temp;
head = &temp;
prev = &temp;

It should be

head =(struct node *)malloc(sizeof(struct node));
prev = head;

You are returning a memory address of the local struct which is stored on the stack. Instead you should request memory from the heap to store the head node and return the address to that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM