You need to enable JavaScript to run this app. 基于给定整数序列创建链表时触发运行时错误的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

基于给定整数序列创建链表时触发运行时错误的问题排查

运行时错误根因

链表构建全程使用栈上局部变量作为节点,生命周期完全不满足链表的存续要求,具体问题点:

  • for循环块内定义的list1 k 是块级栈对象:每轮循环执行结束,块内变量会被栈立刻回收,之前赋值给t->next的对象地址直接变成野指针
  • 链表遍历时沿着失效的野指针读内存,直接触发段错误,表现为运行时崩溃
  • 即便根节点A是main函数作用域下的栈对象,后续串联的所有节点地址全部失效,整个链表结构无法正常访问

关键修正规则:链表节点必须在堆上动态分配,手动控制生命周期,不能依赖栈上临时局部变量构建。

修正后可正常运行的代码

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class list1 {
public:
  int val;
  list1 *next;
  list1(int x) : val(x), next(NULL) {}
};
int main() {
  int n;
  cin >> n;
  if (n <= 0) return 0;
  list1 *head = nullptr;
  list1 *tail = nullptr;
  int temp;
  cin >> temp;
  // 根节点堆上分配
  head = new list1(temp);
  tail = head;
  for (int i = 1; i < n; i++) {
    cin >> temp;
    // 后续节点全部堆上分配
    tail->next = new list1(temp);
    tail = tail->next;
  }
  // 遍历输出
  list1 *x = head;
  while (x != nullptr) {
    cout << x->val << " ";
    list1 *temp_del = x;
    x = x->next;
    // 手动释放堆内存避免泄漏
    delete temp_del;
  }
  cout << endl;
  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 11:06:04