C++ delete array memory without brackets still wor

2020-03-03 07:09发布

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.

3条回答
叼着烟拽天下
2楼-- · 2020-03-03 07:45

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.

查看更多
Rolldiameter
3楼-- · 2020-03-03 07:50

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.

查看更多
▲ chillily
4楼-- · 2020-03-03 07:52

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.

查看更多
登录 后发表回答