LeetCode #148 Sort List空指针访问运行时错误原因排查求助
问题:LeetCode 148题选择排序链表代码运行时错误分析
我针对LeetCode第148题Sort List编写了一段基于选择排序的链表排序C语言代码,代码如下:
struct ListNode* sortList(struct ListNode* head){ struct ListNode *temp, *change; int temp_data; temp = head; change = head->next; //<<<<<<<<<<<<<<<<<<<< while(temp) { change = temp->next; while(change) { if (temp->val > change->val) { temp_data = temp->val; temp->val = change->val; change->val = temp_data; } change = change->next; } temp = temp->next; } return head; }
该代码在Dev C++中运行正常,但提交至LeetCode时出现运行时错误:
Line 13: Char 12: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]
错误指向change = head->next;这一行。请问该错误的成因是什么?
错误成因分析
- 未处理空链表边界场景:LeetCode测试集包含空链表输入(即
head为NULL),此时代码中change = head->next;直接对空指针执行->next成员访问,属于C语言未定义行为,触发运行时错误。 - 本地测试覆盖不全:你在Dev C++中运行正常,是因为本地测试没有传入空链表用例,未触发该边界问题。
另外,代码中change = head->next;这一行完全多余——进入第一个while(temp)循环后,会立刻执行change = temp->next;覆盖该值,直接删除这行代码即可解决空指针访问问题。
内容的提问来源于stack exchange,提问作者Andrew530
相关产品推荐
相关产品推荐

