【问题标题】:Why is the popping out last element in stack resulting in segmentation fault in C?为什么弹出堆栈中的最后一个元素会导致 C 中的分段错误?
【发布时间】:2020-12-15 16:42:22
【问题描述】:

我在 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");
                }
            }

}

我知道有人问过Pop Function In Linked List Stack Results in Segmentation Fault- C 的类似问题,但这对我没有帮助。为什么会出现这个错误?问题是否与上述问题类似。

【问题讨论】:

  • 这些声明节点 *top, *rear, *front, *header;没有意义。
  • 函数显示可以调用未定义的行为。
  • @Vlad fom Moscow 编辑了它
  • 指针top和head互相复制是什么意思?
  • 您需要分别编写堆栈和队列的实现。

标签: c stack singly-linked-list


【解决方案1】:

段错误是因为您的显示功能。在显示功能中,您检查if (ptr-&gt;link == NULL),但您确实应该检查if (ptr == NULL)。如您所见,如果ptrNULL,那么引用ptr-&gt;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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-08
    • 2011-10-22
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多