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]的容量,会导致缓冲区溢出,破坏栈上其他数据,引发崩溃或未定义行为。
修复方向
- 将栈改为字符串数组,比如
char stack[50][50];,每个元素存储一个子表达式字符串。 - 替换
gets为fgets,并处理输入的换行符(比如用strcspn(exp, "\n")截断换行)。 - 处理运算符前先检查栈中是否有至少2个元素,避免空栈访问。
- 用
snprintf或strcat完成字符串拼接,比如:char temp[100]; snprintf(temp, sizeof(temp), "%s%s%c", op1_str, op2_str, exp[i]); - 输出时直接打印栈顶的字符串,使用
printf("%s", stack[top]);。
内容的提问来源于stack exchange,提问作者Rohan_5002
相关产品推荐
相关产品推荐

