第一次做力扣上的題,遇到了一點問題,代碼如下:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* h=(ListNode*)malloc(sizeof(ListNode));
h->next=NULL;
ListNode* c=h;
ListNode* p=NULL;
int sum=0;
while(l1!=NULL||l2!=NULL||sum!=0){
if(l1!=NULL)
{
sum+=l1->val;
l1=l1->next;
}
if(l2!=NULL) {
sum+=l2->val;
l2=l2->next;
}
p=(ListNode*)malloc(sizeof(ListNode));
p->val=sum%10;
p->next=NULL;
c->next=p;
c=c->next;
sum=sum/10;
}
return h->next;
}
};
運行后報錯:-dealloc-mismatch (malloc vs operator delete) on 0x602000000170
#3 0x7f35e799d0b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x602000000170 is located 0 bytes inside of 16-byte region [0x602000000170,0x602000000180)
allocated by thread T0 here:
#4 0x7f35e799d0b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
43HINT: if you don’t care about these errors you may set ASAN_OPTIONS=alloc_dealloc_mismatch=0
43ABORTING
網上查詢后說malloc和free最好結對使用,不然可能造成記憶體泄漏
然后我在回傳前面加上free(p);p=NULL;依然繼續以下的報錯:
42ERROR: AddressSanitizer: heap-use-after-free on address 0x6020000001b8 at pc 0x0000003e5ad0 bp 0x7ffc7a11e270 sp 0x7ffc7a11e268
READ of size 8 at 0x6020000001b8 thread T0
#4 0x7f8731c360b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x6020000001b8 is located 8 bytes inside of 16-byte region [0x6020000001b0,0x6020000001c0)
freed by thread T0 here:
網上說是記憶體釋放后再次被使用,明明沒有被使用啊?
這是為什么呢?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/193113.html
標籤:C++ 語言
