Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c++ - Should new/new[] match delete/delete[]?

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,

Can 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...