int* arr = new int[count];
delete arr;
Why does this work? I've checked and it actually frees the memory. From what I've read I need delete[] arr;
otherwise it won't actually free all the memory.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
You will get undefined behavior. Save this answer.
The general answer is that the C++ runtime stores the number objects allocated (not the bytes allocated) so that when delete[] is called it can execute the right number of destructors.
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.
The difference is not whether or not the allocated memory is properly freed - whether you use
delete
or
delete[]
the memory will still be properly deallocated.
The difference is whether or not the destructors will be properly invoked.
delete // will only invoke the destructor of the first element of the array.
delete[] // will invoke the destructor for *each* element of the array.
This has no practical effect for primitive types like int or float, but when you have an array of some class, the difference can be critical.
Now try it with filling the array with strings of 100 bytes each, and see if it still frees all the allocated memory...
It is undefined behaviour, and as always, sometimes UB will appear to work. In your case, you have no destructor for the objects in the memory, so there is no "further work", just free all the memory [1]. But if you have an object that has a destructor that does something useful, it (probably) won't get called.
You should ALWAYS use delete []
if you used new T[size];
to allocate. Don't mix the two, it's always wrong - just sometimes it HAPPENS to work [just like SOME sizes of spanners in inches works on mm nuts and vice versa - but it's still wrong to use a inches spanner set on metric nuts].
[1] Note that this may work for this particular compiler/C++ library combination. Compiling it with a different compiler, using a different C++ library, or compiling for a different OS may cause it to crash when you try the same thing.
delete and delete [] are actually different operators and to use the wrong one is always an error. The problem is that it often seems fine at the time, but the heap has ben corrupted and you are very likely to experience an apparently unrelated crash later.
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