我正在编写 LeetCode 问题“奇偶链表”的解决方案,可以在此处阅读。
我的代码因错误而未能通过测试用例
================================================================
==31==ERROR: AddressSanitizer: heap-use-after-free on address 0x6020000000d8 at pc 0x0000003d7f1d bp 0x7fff37cf9640 sp 0x7fff37cf9638
READ of size 8 at 0x6020000000d8 thread T0
但是,当我在 Visual Studio 中运行代码来诊断错误时,一切正常。LeetCode 的解决方案在这里:
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head){
return head;
}
ListNode* odd_head = head;
ListNode* even_head = odd_head->next;
if (!even_head){
return head;
}
ListNode* last_odd = odd_head;
ListNode* last_even = even_head;
ListNode* next_node = even_head->next;
bool flag = true;
while(true){
if (!next_node){
break;
}
if (flag){
last_odd -> next = next_node;
last_odd = next_node;
} else {
last_even -> next = next_node;
last_even = next_node;
}
flag = !flag;
next_node = (next_node->next);
}
last_odd->next = even_head;
return odd_head;
}
};
我用来测试上述内容的代码在这里:
#include "oddevenlinkedlist.h"
#include <iostream>
int main() {
ListNode* l1 = new ListNode(1);
ListNode* l2 = new ListNode(2);
l1->next = l2;
ListNode* l3 = new ListNode(3);
l2->next = l3;
ListNode* l4 = new ListNode(4);
l3->next = l4;
ListNode* l5 = new ListNode(5);
l4->next = l5;
Solution solution{};
ListNode* result = solution.oddEvenList(l1);
ListNode* next_node = result;
for (int i = 0; i < 5; ++i) {
std::cout << next_node->val << " ";
next_node = next_node->next;
}
delete l1;
delete l2;
delete l3;
delete l4;
delete l5;
return 0;
}
如果您想对此进行测试,您将需要ListNode
此处的 a 定义:
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
因为该代码适用于我的编译器,所以我无法诊断错误。虽然我当然希望有人能识别错误,但我的问题是:为什么 MSVS 没有捕捉到“heap-use-after-free”错误?