C语言栈实现出现segmentation fault (core dumped)错误求助
栈实现中的段错误问题分析与修复
问题背景
初学C语言的开发者在实现栈的push和pop基本功能时,编译运行后出现segmentation fault (core dumped)错误,代码如下:
#include <stdio.h> #include <string.h> #define MAXSIZE 100 struct stack { int a[MAXSIZE]; int Top; }; /* * Add an element to stack */ void push(struct stack *pu) { int element; printf("element: "); scanf(" %d", &element); pu->a[pu->Top] = element; if(pu->a[pu->Top] >= MAXSIZE -1) { printf("stack is full\n"); } else{ // Prints out the top most element printf("Top is: %d\n", pu->a[pu->Top]); } } /* * Pop/Remove an element from the stack */ void pop(struct stack *po) { printf("You're in pop function.\n"); if(po->Top <= -1) { printf("stack is underflow"); } else{ printf("%d will be remove from the stack", po->a[po->Top]); printf("%d has been removed from the stack", po->a[po->Top]); } } void Second(char x[]) { struct stack pa; if(x[1] == 'u') { push(&pa); } else if(x[1] == 'o'){ pop(&pa); } } int main() { int element; char s[MAXSIZE]; struct stack ps; ps.Top = -1; printf("Push or Pop?\n"); scanf("%s", &s); Second(s); }
错误原因分析
- 栈结构体未初始化:
Second函数中定义的struct stack pa没有初始化Top成员,其值为随机垃圾值。执行push或pop时,访问pu->a[pu->Top]会因下标越界触发段错误。 - scanf参数错误:
scanf("%s", &s);中s是数组名,本身就是指向数组首元素的指针,不需要取地址操作。传入&s会导致指针类型不匹配,可能破坏内存。 - push函数逻辑错误:
- 栈满判断条件错误:应该检查栈顶指针
pu->Top >= MAXSIZE -1,而非栈顶元素的值pu->a[pu->Top] >= MAXSIZE -1。 - 操作顺序错误:应先判断栈是否已满,再添加元素,且添加后需要将
Top指针自增。
- 栈满判断条件错误:应该检查栈顶指针
- pop函数逻辑缺失:仅打印了栈顶元素,未将
Top指针自减,没有完成弹出元素的实际操作。
修复后的代码
#include <stdio.h> #include <string.h> #define MAXSIZE 100 struct stack { int a[MAXSIZE]; int Top; }; /* * Add an element to stack */ void push(struct stack *pu) { // 先判断栈是否已满 if(pu->Top >= MAXSIZE -1) { printf("stack is full\n"); return; } int element; printf("element: "); scanf(" %d", &element); // Top先自增,再赋值 pu->Top++; pu->a[pu->Top] = element; printf("Top is: %d\n", pu->a[pu->Top]); } /* * Pop/Remove an element from the stack */ void pop(struct stack *po) { printf("You're in pop function.\n"); if(po->Top <= -1) { printf("stack is underflow\n"); return; } printf("%d will be removed from the stack\n", po->a[po->Top]); // Top自减完成弹出操作 po->Top--; printf("Top is now: %d\n", po->Top >= -1 ? (po->Top == -1 ? -1 : po->a[po->Top]) : -1); } void Second(char x[], struct stack *stk) { if(x[0] == 'P' && x[1] == 'u') // 更严谨的判断,避免输入其他字符串出错 { push(stk); } else if(x[0] == 'P' && x[1] == 'o'){ pop(stk); } else { printf("Invalid input, please enter Push or Pop\n"); } } int main() { char s[MAXSIZE]; struct stack ps; ps.Top = -1; // 初始化栈顶指针为-1,表示空栈 printf("Push or Pop?\n"); scanf("%s", s); // 去掉多余的&符号 Second(s, &ps); // 将主函数中初始化好的栈传入Second函数 }
关键修复说明
- 统一使用主函数中初始化好的栈实例,避免在
Second函数中创建未初始化的栈。 - 修正push函数的操作顺序:先判断栈满,再自增Top、赋值元素。
- 完善pop函数:添加Top自减操作,完成弹出逻辑。
- 修正scanf的参数错误,同时增强输入判断的严谨性。
- 所有分支添加
return,避免后续不必要的执行。
内容的提问来源于stack exchange,提问作者TILTNGO
相关产品推荐
相关产品推荐

