I have the following code to reverse a linked list. Why do I get a runtime error:
AddressSanitizer:DEADLYSIGNAL
=================================================================
==31==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000010 (pc 0x000000370a97 bp 0x7fffed631a10 sp 0x7fffed6318c0 T0)
==31==The signal is caused by a READ memory access.
==31==Hint: address points to the zero page.
#4 0x7f165e0300b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
AddressSanitizer can not provide additional info.
==31==ABORTING
IF I comment out the line "cout<<pre<<endl;"?
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return head;
ListNode* temp = head;
ListNode* pre;
cout<<pre<<endl;
ListNode* cur = head;
while(cur->next){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
cur->next = pre;
return cur;
}
};
if I don't comment out the line, cout would print a random address each time, and the program would successfully reverse the linked list without any errors. Link to the problem: https://leetcode.com/problems/reverse-linked-list/