从堆栈中检索项目时 C 程序崩溃

标签 c pointers stack

以下代码在第二次 Pop() 调用时崩溃。我是 C 的新手,现在我已经盯着这段代码看了一个多小时了,但我看不到错误。有什么想法可以帮助我解决此代码崩溃的原因吗?

#include <stdio.h>

#define StackDataSize 100

typedef struct Stack
{
    int index;
    void *data[StackDataSize];
} Stack;

void* Pop(Stack *s)
{
    if(s->index >= 0)
    {
        return s->data[s->index--];
    }
    else
    {
        fprintf(stderr, "ERROR: Stack Empty\n");
        return NULL;
    }
}

void Push(Stack *s, void *v)
{
    if(s->index < StackDataSize)
    {
        s->data[++s->index] = v;
    }
    else
    {
        fprintf(stderr, "ERROR: Stack Full\n");
    }
}

int main(void)
{
    Stack s = {-1}, *intstack = &s;

    int x = 123456;
    Push(intstack, &x);

    printf("%d\n", *(int*)Pop(intstack));
    printf("%d\n", *(int*)Pop(intstack));

    return 0;
}

最佳答案

在第二次 Pop 时,栈为空,如果栈为空,Pop 返回 NULL。

所以在第二行:

printf("%d\n", *(int*)Pop(intstack));

您正在取消引用 NULL 作为指向 int 的指针。

printf("%d\n", *(int*)NULL );

关于从堆栈中检索项目时 C 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2017002/

相关文章:

c - 单击按钮时在 WPF 中添加动态控件

计算并打印 C 中大 N 的 (2^N-1) mod (10^9 + 7)

c - strstr() 函数获取位置

c - 使用 intptr_t 而不是 void*?

c - 数组和指针 : segmentation fault

c - 指针类型转换如何在 C 中工作

标量类型的复合文字

css - 将 DIV 堆叠在一起?

bios中断调用所需的堆栈大小

c++ - 我正在用c++创建一个具有撤消和清除功能的计算器。使用堆栈