c - 如何修复此代码中的“分段错误(核心转储)”?
问题描述
我在链表、堆栈和队列中经常遇到这些错误。如果有人能指出我一次又一次犯的错误,那就太好了。
这是我编写的代码。
#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)
. 我已经尝试在多台机器和编译器上运行代码,但仍然没有区别。
解决方案
作为一项规则,请避免使用同名的全局变量和参数,这有点令人困惑,并且可能会导致您看到的问题。
正如您的代码现在所代表的那样,当您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);
}
}
推荐阅读
- python - 您如何将 100 个术语列表汇总为少量(约 5 个)重要术语?
- javascript - .then() 子句未执行
- angular - Angular material 10 日期选择器(mat-datepicker)与其他输入字段不对齐
- python - PyGame:对位于两个列表中的多个图像使用 img.get_rect() 并为它们使用唯一的宽度和高度变量
- ios - 集合视图单元格背景颜色在 reloadData() Swift/Firebase 上反转
- pandas - 从日期时间列中提取月份和年份的问题
- python - 如何运行 MySQL 数据库作为 Rasa 服务器的跟踪器存储?
- javascript - "?." 是什么意思?(问号后的点)在 JS 中的意思
- ionic4 - 离子 5 电容器无法打开文件
- python - 使用 VS Code 调试 python 文件。断点抛出异常,断点被忽略