I have a question regarding deleting an array from heap memory. In a book and on this blog and in other resources such as this one, I read that for removing an array from the heap we must use the []
after the delete
keyword so that if we do not use []
we will have leak memory.
for example, consider the code below.
//constructing array
int *s = new int[10];
// deleting array from heap
delete [] s;
I tested this little program in Linux by using the valgrind
package to check how much memory leaks we have which are caused by bad coding. By below command in Linux, I saw that everything is alright
sudo valgrind --leak-check=full ./<path_to_exe_file>
this is the output of the Linux command
==4565== HEAP SUMMARY:
==4565== in use at exit: 0 bytes in 0 blocks
==4565== total heap usage: 1 allocs, 1 frees, 40 bytes allocated
==4565==
==4565== All heap blocks were freed -- no leaks are possible
However, My question arose when I tried to use the delete
without using []
. The output from valgrind
shows that all heap memory has been freed. Is this correct? or valgrind
didn't realize the heap wasn't freed and some part of the array is still in there!!? If valgrind
cannot detect this kind of memory leak, is there any other package that can detect this?
Calling delete
on an array without using []
results in Undefined Behaviour. The Undefined Behaviour might be that the array is correctly deleted, which appears to be what you observed. You can't rely on this, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With