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

C语言前缀转后缀表达式代码崩溃无输出求助

前缀转后缀表达式程序崩溃问题排查

问题描述

编写程序将给定前缀表达式转换为等价后缀表达式并使用栈求值,程序可接收输入,但输入前缀表达式后立刻崩溃返回终端,无输出。

原代码

//header files
#include<stdio.h>
#include<string.h>

//global variables
char stack[50];
int top = -1;

void push(char s)
{
stack[++top]=s;
}

//function to pop an element
char pop()
{
return stack[top--];
}

// funtion to check if the character is operator or not
int is_operator(char x)
{
    switch (x)
    {
        case '+':
        case '-':
        case '/':
        case '*':
    return 1;
    }
    return 0;
}

//function to Convert prefix to Postfix
void convert()
{
    int i,l;
    char op1,op2,tmp;

    char exp[50];
    printf("Enter the prefix expression: ");
    gets(exp);

    //length of expression
    l = strlen(exp);
    //scanning from right to left
    for(i = l - 1; i >= 0; i--)
    {
        //checking if the symbol is an operator
        if (is_operator(exp[i]))
        {
            //popping two operands from stack
            op1 = stack[top];
            pop();
            op2 = stack[top];
            pop();
            //concating the operands and operator
            tmp = op1 + op2 + exp[i];
            //Pushing the temporary string to stack
            push(tmp);
        }
        //if it is an operand
        else
        {
            //push the operand to the stack
            push((exp[i]));
        }
    }
    //printf("The postfix expression is: %s",stack[top].c_str());
        printf("%s ",stack[top]);
}

//main function
int main()
{
    
    convert();
    return 0;
}

错误原因与排查

  • 空栈未检查导致数组越界:处理运算符时直接读取stack[top]并执行pop(),若栈中元素不足2个(比如输入格式错误或处理逻辑问题),会访问stack[-1],触发数组越界,直接导致程序崩溃。
  • 字符串拼接逻辑完全错误:用tmp = op1 + op2 + exp[i];试图拼接字符,但这是ASCII值的算术相加,不是字符串拼接。得到的结果是一个整数,赋值给char类型变量后是无效字符,压入栈后会引发后续操作错误。
  • 栈存储类型错误:前缀转后缀过程中,栈需要存储的是子表达式字符串,而非单个字符。原代码的char stack[50]只能存单个字符,无法保存拼接后的子串,必然导致数据丢失和内存访问异常。
  • 输出格式不匹配:用printf("%s ",stack[top]);输出,但stack[top]是单个字符,%s要求传入字符串指针,会读取内存中未知数据直到遇到\0,触发内存访问违规。
  • 使用不安全的gets函数:gets不检查输入长度,若输入表达式超过exp[50]的容量,会导致缓冲区溢出,破坏栈上其他数据,引发崩溃或未定义行为。

修复方向

  1. 将栈改为字符串数组,比如char stack[50][50];,每个元素存储一个子表达式字符串。
  2. 替换gets为fgets,并处理输入的换行符(比如用strcspn(exp, "\n")截断换行)。
  3. 处理运算符前先检查栈中是否有至少2个元素,避免空栈访问。
  4. 用snprintf或strcat完成字符串拼接,比如:
    char temp[100];
    snprintf(temp, sizeof(temp), "%s%s%c", op1_str, op2_str, exp[i]);
    
  5. 输出时直接打印栈顶的字符串,使用printf("%s", stack[top]);。

内容的提问来源于stack exchange,提问作者Rohan_5002

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:15:37