First, delete
frees the memory pointed to by the pointer, but does not touch the pointer itself. It will continue to point to where the data was before.
By analyzing your code we have A
to get the pointer to a newly allocated memory, a list. Then you make B
point to the same location as A
. Then it deletes the list in memory pointed to by A
, which is the same as B
. Now both pointers point to an invalid region of memory. When attempting to execute delete B
you invoke undefined behavior . Anything can happen from here, most likely nasal demons .
This problem is generally known as double free and various memory analysis tools can detect this error in your program, such as address sanitizer . Compiling your code with g++ main.cpp -o main -fsanitize=address
and executing the result, I have the second output:
=================================================================
==11122== ERROR: AddressSanitizer: attempting double-free on 0x60040000dff0:
#0 0x7ff3c90e39da (/usr/lib/x86_64-linux-gnu/libasan.so.0.0.0+0x119da)
#1 0x400b89 (/home/guilherme/main+0x400b89)
#2 0x7ff3c8a29ec4 (/lib/x86_64-linux-gnu/libc-2.19.so+0x21ec4)
0x60040000dff0 is located 0 bytes inside of 16-byte region [0x60040000dff0,0x60040000e000)
freed by thread T0 here:
#0 0x7ff3c90e3a4a (/usr/lib/x86_64-linux-gnu/libasan.so.0.0.0+0x11a4a)
#1 0x400b7d (/home/guilherme/main+0x400b7d)
#2 0x7ff3c8a29ec4 (/lib/x86_64-linux-gnu/libc-2.19.so+0x21ec4)
previously allocated by thread T0 here:
#0 0x7ff3c90e388a (/usr/lib/x86_64-linux-gnu/libasan.so.0.0.0+0x1188a)
#1 0x400b5e (/home/guilherme/main+0x400b5e)
#2 0x7ff3c8a29ec4 (/lib/x86_64-linux-gnu/libc-2.19.so+0x21ec4)
==11122== ABORTING