LeetCode合并两个有序链表C代码遍历至链表尾触发内存对齐错误
问题背景
我正在LeetCode平台解答21. Merge Two Sorted Lists题目,题目要求如下:给定两个已按升序排列的链表,需将二者合并为一个同样按升序排列的单链表。
我的实现代码如下:
struct ListNode *sortList(struct ListNode *headList) { struct ListNode *ptrHead = headList; int temp; if(headList == NULL) return NULL; while(ptrHead->next != NULL){ if(ptrHead->val > ptrHead->next->val){ temp = ptrHead->val; ptrHead->val = ptrHead->next->val; ptrHead->next->val = temp; ptrHead = headList; }else{ ptrHead = ptrHead->next; } } return headList; } void addNode(struct ListNode **list, int data){ struct ListNode *newNode = (struct ListNode *) malloc(sizeof (struct ListNode)), *temp = NULL; if((*list) == NULL){ newNode->val = data; newNode->next = NULL; (*list) = newNode; }else{ temp = (*list); while (temp->next != NULL){ temp = temp->next; } newNode->val = data; temp->next = newNode; } } struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2){ struct ListNode *newList = NULL; while (l1 != NULL){ addNode(&newList, l1->val); l1 = l1->next; } while (l2 != NULL){ addNode(&newList, l2->val); l2 = l2->next; } return sortList(newList); }
我在本地环境运行上述代码未出现异常,但提交到LeetCode平台运行时抛出错误,遍历链表到最后一个元素时触发报错,具体报错信息如下:
Line 19: Char 20: runtime error: member access within misaligned address 0xbebebebebebebebe for type 'struct ListNode', which requires 8 byte alignment [solution.c] 0xbebebebebebebebe: note: pointer points here <memory cannot be printed>
错误原因
- 问题根源在
addNode函数的新节点初始化逻辑:当向非空链表追加节点时,你只设置了新节点的val字段,没有将新节点的next指针显式赋值为NULL。 malloc申请内存时不会自动清空内存内容,新节点的next字段会保留对应内存位置的原有随机值。部分本地运行环境下,刚申请到的内存残留值恰好为0(即与NULL值等价),所以本地测试不会触发异常;但LeetCode判题环境会对未初始化的内存填充特殊标记值(本次报错里的0xbebebebebebebebe就是这类标记),用来识别未初始化内存的非法访问。- 后续
sortList函数遍历链表时,走到最后一个追加的节点就会读到这个野指针值,尝试访问这个非法地址对应的结构体成员时,就会触发内存对齐错误、非法内存访问的运行时报错。
修复方法
只需要在addNode的非空链表追加分支里,补全新节点的next指针初始化即可:
// else分支修改后 }else{ temp = (*list); while (temp->next != NULL){ temp = temp->next; } newNode->val = data; newNode->next = NULL; // 补全这行初始化 temp->next = newNode; }
补充说明:当前实现先拼接两个链表再做冒泡排序的时间复杂度是O(n²),这道题最优解是利用两个输入链表本身有序的特性,用双指针做线性合并,时间复杂度可以降到O(n),不过这属于性能优化范畴,不是本次运行错误的直接诱因。
内容的提问来源于stack exchange,提问作者Benedetto Testa
相关产品推荐
相关产品推荐

