First of all, delete
releases the memory pointed by the pointer, but does not touch the pointer itself. It will continue to point to where the data was before.
Analyzing your code we have to A
will receive the pointer to a newly allocated memory, a list. Next you do B
point to the same location as A
. Then delete the list in the memory pointed by A
, which is the same pointed out by B
. Now both pointers point to an invalid memory region. When trying to run delete B
you invoke Undefined behavior. Whatever can happen from here, most likely nasal demons.
This problem is commonly known as double free and various memory analysis tools can detect this error in your program, such as Sanitizer address. Compiling your code with g++ main.cpp -o main -fsanitize=address
and executing the result, I have the second exit:
=================================================================
==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
Choose to use
#include <iostream>
with<iostream>
instead of"iostream"
. When you use quotes, the compiler will searchiostream
in the directory of your program and, as you won’t find, (only then) will search in the system directory.– Lucas Lima
To complement Lucas Nunes' comment, use double quotes to include only your local files. Regarding your question, when using
delete
memory is released but content is not changed immediately. This can cause undefined behavior. In this case, it is valid to delete the pointerdelete B;
and then define as nullB = NULL;
. In any case, whenever possible use smart pointers. In this guide you can find some good practices in C++.– KelvinS