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

C++实现简单链表栈触发Segmentation fault 11错误如何排查

链表实现栈压入操作触发段错误排查

问题描述

C++初学者基于链表实现简单栈结构,已知段错误通常关联内存访问异常,但仅编写单元素压入逻辑时,运行就抛出Segmentation fault: 11错误,无法定位问题,原始代码如下:

#include <iostream>
using namespace std;

struct Node{
     int data;
     struct Node* link;
 };

Node* Push(int, Node*);

int main(){
    struct Node* top = nullptr;
    top = Push(3, top);
}

Node* Push(int data,  Node* top){
    struct Node* temp = (struct Node*) new Node();
    temp->data = data;
    temp->link = top->link;
    top = temp;
    return top;
}

错误原因

段错误由空指针的非法访问直接导致:

  • 初始状态栈为空,main函数里传入Push的top是nullptr(空指针),没有对应的实际内存空间
  • Push函数中执行temp->link = top->link;时,尝试读取空指针top的link成员,属于非法内存访问,直接触发段错误
  • 同时压栈逻辑本身存在错误:新压入的节点会成为新的栈顶,它的link指针应该直接指向旧栈顶节点,而非旧栈顶节点的link成员。

修复方法

  • 修正压栈时的指针赋值逻辑:新节点的link直接指向传入的旧top指针即可,空栈场景下旧top为nullptr,直接赋值完全合法
  • 移除不必要的C风格指针强转:C++中new返回的指针类型和目标类型匹配,冗余强转反而可能隐藏潜在类型问题

修复后的可运行代码:

#include <iostream>
using namespace std;

struct Node{
     int data;
     struct Node* link;
 };

Node* Push(int, Node*);

int main(){
    struct Node* top = nullptr;
    top = Push(3, top);
    // 测试验证
    cout << "栈顶元素为:" << top->data << endl;
    // 实际使用时记得补充内存释放逻辑,避免内存泄漏
    return 0;
}

Node* Push(int data,  Node* top){
    Node* temp = new Node();
    temp->data = data;
    temp->link = top;
    return temp;
}

注:上述代码直接返回新节点作为新栈顶即可,原函数内给局部参数top赋值的操作对外没有实际效果,可以省略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 09:22:01