ans
is allocated on the stack, locally. As soon as you return from addTwoNumbers
, there is no guarantee the data is still there, i.e. it's undefined behavior. GCC warns about it:
<source>: In function 'ListNode* addTwoNumbers(ListNode*, ListNode*)':
<source>:45:12: warning: address of local variable 'ans' returned [-Wreturn-local-addr]
45 | return &ans;
| ^~~~
<source>:18:14: note: declared here
18 | ListNode ans;
| ^~~
So, you must declare ans
on the heap, using new
:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode();
ListNode* ptr = ans;
// ...
return ans;
}
It now runs and outputs a result.
However, as the other answer has pointed out, you're leaking memory. While it probably won't be a problem for a LeetCode problem, it's a problem for real-life code. Using an smart pointer, such as std::unique_ptr
, or doing your own RAII wrapper, would be preferable solutions over calling delete
for each pointer on the list.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…