C语言用临时栈排序链表实现的栈时出现段错误
段错误成因排查
- 栈操作函数全踩了值传递的坑,原栈指针从头到尾没被正确修改
C语言函数传参全是值拷贝模式,你写的init/push/pop全都把node*当形参,函数内部修改的都是传进来的指针副本,根本碰不到main函数里定义的top变量:- 调用
init(top)时,只是把top的随机值拷贝给形参t,把t设为NULL的操作完全影响不到main里的top,top从始至终都是未初始化的野指针 push里malloc完新节点,把局部指针t指向新节点,main里的top一点没更新,等于申请的内存根本没有挂载到栈结构上pop里把局部指针s往后移、释放节点的操作,同样修改不了调用处的栈顶指针,整个栈的结构完全是混乱的
- 调用
- 排序函数里的临时栈指针没初始化
代码里写node *temp;根本没赋值,是存储值随机的野指针,后面直接用它做空栈判断、push元素、取栈顶值,直接触发非法内存访问,这就是段错误的直接触发点 - 没有做空指针校验
topSt函数不管栈是不是空,直接解引用取val,一旦传进来的栈是空的,直接触发空指针段错误。
修复方案
- 所有需要修改栈顶指针的函数,统一改成传
node**(也就是把栈顶指针的内存地址传进去),直接通过地址写入修改原指针,保证栈结构的变更能真正传递到调用位置 - 所有栈指针定义的时候直接给初值
NULL,和空栈的判定规则对齐,杜绝野指针 - 栈操作函数内部增加非空判断,避免硬解引用空指针
修复后的可运行代码
#include <stdio.h> #include <stdlib.h> typedef struct Node{ int val; struct Node*next; }node; int isempty(node *n){//check if empty return n == NULL; } void push(node **t, int val){ node *temp = malloc(sizeof(node)); if(temp == NULL){ exit(EXIT_FAILURE); } temp->val = val; temp->next = *t; *t = temp; } void pop(node **s){ if(isempty(*s)) return; node *temp = *s; *s = (*s)->next; free(temp); } int topSt(node *s){//returns top of the stack if(isempty(s)){ exit(EXIT_FAILURE); } return s->val; } node *sortStack(node *input){//sorting the stack node *temp = NULL; // 临时栈初始化为空 int t; while(!isempty(input)){ t = topSt(input); pop(&input); while(!isempty(temp) && topSt(temp) > t){ push(&input, topSt(temp)); pop(&temp); } push(&temp, t); } return temp; } void display(node *head){//display the stack's elements while(head != NULL){ printf("%d\n", head->val); head = head->next; } } int main(){ node *top = NULL; // 显式初始化空栈 push(&top,9); push(&top,45); push(&top,21); push(&top,5); node *sorted = sortStack(top); display(sorted); }
代码运行输出(按栈顶到栈底顺序打印):
45
21
9
5
内容的提问来源于stack exchange,提问作者raylyn
相关产品推荐
相关产品推荐

