首页 > 解决方案 > 如何修复此代码中的“分段错误(核心转储)”?

问题描述

我在链表、堆栈和队列中经常遇到这些错误。如果有人能指出我一次又一次犯的错误,那就太好了。

这是我编写的代码。

#include <stdio.h>
#include <malloc.h>

struct Node
{
    int data;
    struct Node* next;
}*front=NULL,*rear=NULL;
void enqueue(struct Node *front,struct Node *rear,int ele)
{
    struct Node *temp=(struct Node*)malloc(sizeof(struct Node));
    struct Node* ptr=front;
    if (temp==NULL)
        printf("Overflow");
    else
    {
        if (front==NULL)
        {
    temp->data=ele;
    temp->next=NULL;
    front=temp;
    printf("%d",front->data);
    }
    else
    {
        printf("Srishti");
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        temp->next=front;
        ptr->next=temp;
        rear=temp;
    }
}
    }
void dequeue()
{
    struct Node *temp=front;
    if(front!=NULL && front->next!=NULL)
    {
        rear->next=front->next;
        front=front->next;
    }
}

void display()
{
    struct Node *temp=front;
    while(temp->next!=front)
    {
        printf("%d",temp->data);
        temp=temp->next;
    }
    printf("%d",rear->data);
}

void main()
{
    int n,i;
    for(i=0;i<3;i++)
    {
        printf("Enter Element");
        scanf("%d",&n);
        enqueue(front,rear,n);
    }

display();

}

我看到的输出总是Segmentation Fault (core dumped). 我已经尝试在多台机器和编译器上运行代码,但仍然没有区别。

标签: clinked-listqueue

解决方案


作为一项规则,请避免使用同名的全局变量和参数,这有点令人困惑,并且可能会导致您看到的问题。

正如您的代码现在所代表的那样,当您front在函数内部进行更改时,您实际上并没有更改全局变量前面,而是更改了副本。

所以要么将前后的地址传递给函数,要么完全删除参数。

void enqueue(struct Node **front,struct Node **rear,int ele)
{
  struct Node *temp=(struct Node*)malloc(sizeof(struct Node));
  struct Node* ptr=*front;
...

if (front == NULL)
{
  temp->data = ele;
  temp->next = NULL;
  *front = temp;      // this will actually change front
  printf ("%d", front->data);
}

并将其称为

int n, i;
for (i = 0; i < 3; i++)
{
  printf ("Enter Element");
  // scanf ("%d", &n); avoid using scanf like this, use instead fgets
  char line[32];
  if (fgets(line, sizeof(line), stdin) != NULL)
  { 
    int n = atoi(line); 
    enqueue (&front, &rear, n);
  }
}  

推荐阅读