简体   繁体   English

单链表C程序中的分段错误

[英]Segmentation fault in singly linked list C program

In this code below, when I comment out the first and second call to display() function in main, It works fine. 在下面的代码中,当我在main中注释掉第一次和第二次调用display()函数时,它工作正常。 But without commenting, after adding 2nd element it says - segmentation fault . 但是没有评论,在添加第二个元素后它说 - 分段错误

I am new to pointers. 我是新手。 Please suggest what might be wrong. 请建议可能出错的地方。

#include<stdio.h>
#include<malloc.h>
//-------------------------------------------------
struct node
{
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------

void creat()
{

  struct node *new_node,*current;

  new_node=(struct node *)malloc(sizeof(struct node));

  printf("\nEnter the data : ");
  scanf("%d",&new_node->data);
  new_node->next=NULL;

  if(start==NULL)
  {
  start=new_node;
  current=new_node;
  }
  else
  {
  current->next=new_node;
  current=new_node;
  }
}
//------------------------------------------------------------------
void display()
{
struct node *new_node;
 printf("\nThe Linked List : ");
 new_node=start;
 while(new_node!=NULL)
   {
   printf("%d--->",new_node->data);
   new_node=new_node->next;
   }
  printf("NULL\n\n");
}
//----------------------------------------------------
void main()
{
creat();
display();
creat();
display();
creat();
display();
}

output -> 输出 - >

 $./a.out

Enter the data : 4

The Linked List : 4--->NULL


Enter the data : 6
Segmentation fault (core dumped)

This is happening because of current->next=new_node; 这是因为current->next=new_node; in else block. 在else块中。 When you enter data second time start is declared global so its value persists between function call but as current is declared within fuunction it's scope is limited to function only. 当您第二次输入数据时, start被声明为全局,因此它的值在函数调用之间持续存在,但是当在函数内声明current它的范围仅限于函数。 So when you enter data second time current is null so accessing current->next causes segmentation fault. 因此,当您第二次输入数据时, current为空,因此访问current->next会导致分段错误。
So declare current node after start variable. 所以在start变量之后声明current节点。

Second time you call creat , you are using an ininitialized current . 第二次调用creat ,您使用的是未初始化的current

current_node is a local variable with auto storage. current_node是具有自动存储的本地变量。 When you return from the function, it gets deleted. 从函数返回时,它将被删除。

Try adding 尝试添加

struct node* current = NULL;

right after you define start . 在你定义start Then, remove it from creat . 然后,将其从creat删除。

The offending code is: 违规代码是:

       current->next=new_node;

You are dereferencing a NUll pointer which is illegal. 您正在取消引用非法的NUll指针。 What you should have done was to declare current as a global variable as well: 你应该做的是将current声明为全局变量:

struct node
{
int data;
struct node *next;
}*start=NULL,*current=NULL;

This will fix your display issue as well. 这也将解决您的显示问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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