C++链表按姓名删除节点触发段错误,请求排查修复
C++链表删除节点触发Segmentation Fault的排查与修复
问题根源分析
你遇到的code=3221225477(Windows平台段错误等价码)和Segmentation fault,触发点在prev->next = temp->next,核心原因是**prev指针为空或指向无效内存**,常见场景包括:
- 要删除的是链表头节点,但代码未处理这种特殊情况,导致
prev未初始化就被访问 - 遍历链表时
prev未正确跟随temp指针移动,导致prev指向野指针 - 未检查
temp是否为空(没找到目标节点时),直接操作temp->next引发错误
修复方案与代码示例
以下是修正后的完整链表实现代码,重点修复了deletePerson方法:
#include <iostream> #include <string> using namespace std; class Node { public: string name; int age; Node* next; Node(string n, int a) : name(n), age(a), next(nullptr) {} }; class LinkedList { private: Node* head; public: LinkedList() : head(nullptr) {} void addPerson(string name, int age) { Node* newNode = new Node(name, age); if (head == nullptr) { head = newNode; return; } Node* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newNode; } void deletePerson(string targetName) { // 链表为空,直接返回 if (head == nullptr) return; Node* temp = head; Node* prev = nullptr; // 处理头节点为目标节点的情况 if (temp->name == targetName) { head = temp->next; delete temp; return; } // 遍历寻找目标节点,同时保证prev始终指向temp的前一个有效节点 while (temp != nullptr && temp->name != targetName) { prev = temp; temp = temp->next; } // 未找到目标节点,直接返回 if (temp == nullptr) return; // 执行删除并释放内存 prev->next = temp->next; delete temp; } void printList() { Node* temp = head; while (temp != nullptr) { cout << temp->name << ", " << temp->age << endl; temp = temp->next; } } // 析构函数释放所有节点,避免内存泄漏 ~LinkedList() { Node* temp; while (head != nullptr) { temp = head; head = head->next; delete temp; } } }; int main() { LinkedList list; list.addPerson("David", 45); list.addPerson("John", 23); list.addPerson("Katty", 30); list.addPerson("Stephanie", 25); list.deletePerson("Katty"); list.printList(); return 0; }
关键修复点说明
- 增加链表为空的判断,避免无效遍历
- 单独处理头节点删除的情况,无需访问未初始化的
prev指针 - 遍历条件同时判断
temp != nullptr,防止越界访问野指针 - 找到目标节点后再执行删除操作,避免空指针解引用
- 添加析构函数释放所有节点,修复潜在的内存泄漏问题
运行结果
执行上述代码后,控制台输出符合预期:
David, 45
John, 23
Stephanie, 25
内容的提问来源于stack exchange,提问作者riram
相关产品推荐
相关产品推荐

