I knew that when we allocate memory by using new/new[], then we should release the memory by using the delete/delete[] respectively.
Here is the question,
C开发者_运维百科an I use delete[] to release the memory allocated by new?
For example,
int *pInt3 = new int;
delete [] pInt3;
pInt3 = NULL;
T *pT3 = new T;
delete [] pT3;
pT3 = NULL;
Thank you
No, you should match the non-array form of new
with non-array delete
, and likewise for the array forms.
See the C++ FAQ Lite section on Freestore Management
This is especially good: http://www.parashift.com/c%2B%2B-faq-lite/freestore-mgmt.html#faq-16.12
[16.12] What if I forget the [] when deleteing array allocated via new T[n]?
All life comes to a catastrophic end.
It is the programmer's —not the compiler's— responsibility to get the connection between new T[n] and delete[] p correct. If you get it wrong, neither a compile-time nor a run-time error message will be generated by the compiler. Heap corruption is a likely result. Or worse. Your program will probably die.
I guess that you are not satisfied with anything but a reference to the standard, so here it is.
You can find it under 3.7.3.2 in the Standard for C++03.
3 The value of the first argument supplied to one of the deallocation functions provided in the standard library may be a null pointer value; if so, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(size_t) or operator new(size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator delete[] (void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[] (size_t) or operator new[] (size_t, const std::nothrow_t&) in the standard library.
So the answer to your question is no.
Can I use delete[] to release the memory allocated by new?
Yes you could, but you will be sorry if you do.
精彩评论