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.
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.
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 usednew 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.
The difference is not whether or not the allocated memory is properly freed - whether you use
or
the memory will still be properly deallocated.
The difference is whether or not the destructors will be properly invoked.
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.
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.