I'm trying to write a simple function that swaps the nodes of a linked list (in which the values cannot be changed, just the nodes). Running into memory usage after free errors, and I can't pin it. I'm fairly certain the answer is quite straightforward and easy, I just can't see it right now.
void swapNodes(ListNode* a, ListNode *b){ //does not consider the root case
auto * a1 = a->next;
auto * a2 = a1->next;
auto * b1 = b->next;
auto * b2 = b1->next; // may be nullptr
auto newA = std::make_shared<ListNode>(ListNode(b1->val, a2));
auto newB = std::make_shared<ListNode>(ListNode(a1->val, b2));
a->next = newA.get();
b->next = newB.get();
}
I know it's missing a lot of checks, ignore that for now. Function receives two pointers (ideally references, but I'm restructuring still) to the nodes which need to be swapped.
Getting:
=================================================================
==32==ERROR: AddressSanitizer: heap-use-after-free on address 0x603000000028 at pc 0x000000383abe bp 0x7ffe9bd980f0 sp 0x7ffe9bd980e8
READ of size 8 at 0x603000000028 thread T0
#3 0x7f2499b8c82f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
0x603000000028 is located 24 bytes inside of 32-byte region [0x603000000010,0x603000000030)
freed by thread T0 here:
#7 0x7f2499b8c82f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
previously allocated by thread T0 here:
#10 0x7f2499b8c82f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
Shadow bytes around the buggy address:
0x0c067fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c067fff8000: fa fa fd fd fd[fd]fa fa fd fd fd fd fa fa fa fa
0x0c067fff8010: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Shadow gap: cc
==32==ABORTING
Aucun commentaire:
Enregistrer un commentaire