基于给定整数序列创建链表时触发运行时错误的问题排查
运行时错误根因
链表构建全程使用栈上局部变量作为节点,生命周期完全不满足链表的存续要求,具体问题点:
- 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
相关产品推荐
相关产品推荐

