You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用realloc实现动态数组栈时添加后续元素出现段错误

动态数组栈实现的段错误原因及修复

你的程序首次压栈正常,但后续操作触发段错误,核心问题出在运算符优先级上,以下是具体分析和修复方案:

错误根源

代码中的*stack[*stackSize] = element;一行,由于[]的优先级高于*,实际会被解析为*(stack[*stackSize]):

  • 第一次压栈时,*stackSize为0,stack[0]等价于*stack(指向刚分配的int数组指针),所以*(stack[0])能正确访问第一个元素;
  • 第二次压栈时,*stackSize为1,stack[1]会访问int** stack指针本身的越界内存,直接触发段错误。

stack_pop函数里的int element = *stack[*stackSize];也存在完全相同的优先级问题,必须一并修复。

修复方案

将涉及数组访问的两行代码,调整为先解引用拿到数组指针,再访问索引:

  • push函数中:(*stack)[*stackSize] = element;
  • pop函数中:int element = (*stack)[*stackSize];

此外,main函数中的scanf("%c", &ch);会读取输入后的换行符,导致循环异常,建议改为scanf(" %c", &ch);(前置空格跳过空白字符)。

修复后的完整代码

#include <stdio.h>
#include <stdlib.h>

void stack_push(int **stack, int *stackSize, int element);
int stack_pop(int **stack, int *stackSize);

int main()
{
    char ch;
    int *stack = NULL, stackSize = 0;
    
    do
    {
        printf("\n1. Push\n");
        printf("2. Pop\n");
        printf("Exit (0)\n");
        printf("Enter choice : ");
        scanf(" %c", &ch);

        switch(ch)
        {
            case '1':
                stack_push(&stack, &stackSize, 1);
                break;
            case '2':
                printf("%d\n", stack_pop(&stack, &stackSize));
                break;
            case '0':
                break;
            default:
                // 处理无效输入
                break;
        }
    } while (ch != '0');

    return 0;
}

void stack_push(int **stack, int *stackSize, int element)
{
    if (!*stack)
    {
        *stack = malloc(sizeof(int));
    }
    else
    {
        *stack = realloc(*stack, sizeof(int) * (*stackSize + 1));
    }

    (*stack)[*stackSize] = element;
    *stackSize += 1;
}

int stack_pop(int **stack, int *stackSize)
{
    if (!*stack)
    {
        return -1;
    }
    else
    {
        *stackSize -= 1;
        int element = (*stack)[*stackSize];

        if (*stackSize > 0)
        {
            *stack = realloc(*stack, sizeof(int) * (*stackSize));
        }
        else
        {
            free(*stack);
            *stack = NULL;
        }

        return element;
    }
}

内容的提问来源于stack exchange,提问作者King of the Skies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 11:55:36