C++链表两处Segmentation Fault问题排查求助
问题原因与修复方案
1. pushBack函数的核心问题:新节点next指针未初始化
你创建新Node时,仅赋值了key和info,但next指针是未初始化的野指针。当第二次调用pushBack时,遍历到第一个节点的next(即新创建的节点),此时判断temp->next != NULL会访问野指针,直接触发段错误。
修复方法:创建新节点后必须将next置为nullptr:
ptr = new Node; ptr->key = key; ptr->info = info; ptr->next = nullptr; // 新增这行,初始化next指针
2. print函数的两个问题
- 循环条件错误:
while (ptr->next != NULL)会跳过最后一个节点的打印,且当链表只有一个节点时,ptr->next是野指针,访问它会触发段错误。 - 未处理最后一个节点输出:即使循环正常执行,最后一个节点的
info也不会被打印。
修复方法:修改循环条件为遍历每个节点本身,而非判断下一个节点是否存在:
void Sequence<Key, Info>::print() { if (head != nullptr) { Node *ptr = head; while (ptr != nullptr) // 改为判断当前节点是否为空 { std::cout << ptr->info << std::endl; ptr = ptr->next; } } else { std::cout << "Empty sequence" << std::endl; } }
额外优化建议
- 用
nullptr替代NULL:C++11及以后推荐使用nullptr,类型更安全。 - 完善析构函数:当前析构函数未释放链表节点内存,会导致内存泄漏,可添加如下代码:
~Sequence<Key, Info>() { Node* current = head; while (current != nullptr) { Node* next = current->next; delete current; current = next; } head = nullptr; }
修复后的完整代码
#include <iostream> template <typename Key, typename Info> class Sequence { private: struct Node { Key key; Info info; Node *next; }; Node *head; public: Sequence<Key, Info>() : head(nullptr) {}; // 改用初始化列表更规范 ~Sequence<Key, Info>() { Node* current = head; while (current != nullptr) { Node* next = current->next; delete current; current = next; } head = nullptr; }; void print(); void pushBack(Key key, Info info); }; template <typename Key, typename Info> void Sequence<Key, Info>::pushBack(Key key, Info info) { Node *ptr = new Node; ptr->key = key; ptr->info = info; ptr->next = nullptr; // 初始化next指针 if (head) { Node *temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = ptr; } else { head = ptr; } } template <typename Key, typename Info> void Sequence<Key, Info>::print() { if (head != nullptr) { Node *ptr = head; while (ptr != nullptr) { std::cout << ptr->info << std::endl; ptr = ptr->next; } } else { std::cout << "Empty sequence" << std::endl; } } int main() { Sequence<int, int> seq; seq.pushBack(1, 5); seq.pushBack(2, 6); seq.print(); }
内容的提问来源于stack exchange,提问作者ZaAnanasa
相关产品推荐
相关产品推荐

