Home > Back-end >  Questions about the malloc and free
Questions about the malloc and free

Time:10-27

Do power button on the topic for the first time, met a little problem, the code is as follows:
The class Solution {
Public:
ListNode * addTwoNumbers (ListNode * l1 and l2 ListNode *) {
ListNode * h=(ListNode *) malloc (sizeof (ListNode));
H - & gt; Next=NULL;
ListNode * c=h;
ListNode * p=NULL;
Int sum=0;
While (l1!=NULL | | l2!=NULL | | sum!=0) {
If (l1!=NULL)
{
The sum +=l1 - & gt; Val.
L1=l1 - & gt; Next;
}
If (l2!=NULL) {
The sum +=l2 - & gt; Val.
L2=l2 - & gt; Next;
}
P=(ListNode *) malloc (sizeof (ListNode));
p-> Val=sum % 10;
p-> Next=NULL;
C - & gt; Next=p;
C=c - & gt; Next;
Sum=sum/10;
}
Return h - & gt; Next;
}
};
After the operation error: - dealloc - mismatch (malloc vs operator delete) on 0 x602000000170
# 3 0 x7f35e799d0b2 (/lib/x86_64 - - the gnu/Linux libc. So. 6 + 0 x270b2)
0 x602000000170 is located 0 bytes inside of 16 - byte region [0 x602000000170, 0 x602000000180)
Allocated by the thread T0 here:
# 4 0 x7f35e799d0b2 (/lib/x86_64 - - the gnu/Linux libc. So. 6 + 0 x270b2)
43 hint: if you don 't care about these errors you may set ASAN_OPTIONS=alloc_dealloc_mismatch=0
43 aborting

Online query said after malloc and free the best pair is used, otherwise may cause memory leak
And then I in front of the back to add free (p); P=NULL; Still continue to the following error:
Error: 42 AddressSanitizer: heap - use - after - free on address 0 x6020000001b8 at PC bp x7ffc7a11e270 sp 0 0 0 x0000003e5ad0 x7ffc7a11e268
The READ of the size 8 at 0 x6020000001b8 thread T0
# 4 0 x7f8731c360b2 (/lib/x86_64 - - the gnu/Linux libc. So. 6 + 0 x270b2)
8 bytes 0 x6020000001b8 is located inside of 16 - byte region [0 x6020000001b0, 0 x6020000001c0)
Freed by thread T0 here:
Online that memory is used again after his release, clearly not being used?
Why is this?
  • Related