为什么弹出堆栈中的最后一个元素会导致 C 中的分段错误?
Why is the popping out last element in stack resulting in segmentation fault in C?
我在 C 中创建堆栈操作。但是当我试图弹出最后一个元素时,它导致 SEGMENTATION FAULT。
代码
#include <stdio.h>
#include <stdlib.h>
typedef struct node1
{
int data;
struct node1 *link;
} node;
node *top,*header;
void push()
{
node *temp = (node *)malloc(sizeof(node));
printf("PUSH : ");
scanf("%d", &temp->data);
if (header == NULL)
{
top = temp;
header = temp;
temp->link = NULL;
}
else
{
temp->link = header;
header = temp;
top = temp;
}
}
void pop()
{
if (header == NULL)
printf("Stack Empty");
else
{
node *ptr = top;
top = header = top->link;
free(ptr);
}
}
void display()
{
node *ptr = header;
while (1)
{
if (ptr->link == NULL)
{
printf("%d", ptr->data);
break;
}
printf("%d", ptr->data);
ptr = ptr->link;
printf("->");
}
printf("\n\n");
}
int main()
{
printf("\nSTACK :\n\n");
while (1)
{
int choice;
printf("1.Push 2. Pop (Press ctrl + C to exit ): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
display();
break;
case 2:
pop();
display();
break;
default:
printf("Wrong Entry\n\n");
}
}
}
我知道有人问过类似的问题 ,但它对我没有帮助。为什么会出现这个错误?是不是跟上面提到的问题类似呢
段错误是因为你的显示功能。在显示功能中,您检查了 if (ptr->link == NULL)
,但您实际上应该检查 if (ptr == NULL)
。如您所见,如果 ptr
是 NULL
,那么引用 ptr->link
将导致段错误。
在显示函数的 while 循环开始时,您可以尝试:
if (ptr == NULL) break;
。更好的是,尝试检查 ptr
是否为 NULL
作为 while 条件:
void display()
{
node *ptr = header;
while (ptr)
{
if (ptr->link == NULL)
{
printf("%d", ptr->data);
break;
}
printf("%d", ptr->data);
ptr = ptr->link;
printf("->");
}
printf("\n\n");
}
我在 C 中创建堆栈操作。但是当我试图弹出最后一个元素时,它导致 SEGMENTATION FAULT。
代码
#include <stdio.h>
#include <stdlib.h>
typedef struct node1
{
int data;
struct node1 *link;
} node;
node *top,*header;
void push()
{
node *temp = (node *)malloc(sizeof(node));
printf("PUSH : ");
scanf("%d", &temp->data);
if (header == NULL)
{
top = temp;
header = temp;
temp->link = NULL;
}
else
{
temp->link = header;
header = temp;
top = temp;
}
}
void pop()
{
if (header == NULL)
printf("Stack Empty");
else
{
node *ptr = top;
top = header = top->link;
free(ptr);
}
}
void display()
{
node *ptr = header;
while (1)
{
if (ptr->link == NULL)
{
printf("%d", ptr->data);
break;
}
printf("%d", ptr->data);
ptr = ptr->link;
printf("->");
}
printf("\n\n");
}
int main()
{
printf("\nSTACK :\n\n");
while (1)
{
int choice;
printf("1.Push 2. Pop (Press ctrl + C to exit ): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
display();
break;
case 2:
pop();
display();
break;
default:
printf("Wrong Entry\n\n");
}
}
}
我知道有人问过类似的问题
段错误是因为你的显示功能。在显示功能中,您检查了 if (ptr->link == NULL)
,但您实际上应该检查 if (ptr == NULL)
。如您所见,如果 ptr
是 NULL
,那么引用 ptr->link
将导致段错误。
在显示函数的 while 循环开始时,您可以尝试:
if (ptr == NULL) break;
。更好的是,尝试检查 ptr
是否为 NULL
作为 while 条件:
void display()
{
node *ptr = header;
while (ptr)
{
if (ptr->link == NULL)
{
printf("%d", ptr->data);
break;
}
printf("%d", ptr->data);
ptr = ptr->link;
printf("->");
}
printf("\n\n");
}