What does the following code do?
obj *x = new obj[100];
delete x; // Note the omission of []
Does it delete only the first element in the array?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Even though it is undefined behavior, you should probably take note of the most likely result (for the sake of debugging such issues).
When you create an array via
new Object[100], the memory is first allocated. The default behavior (provided there were no overrides to the default allocator) is to simply callmalloc(100 * sizeof(Object)). After that, the constructor forObjectneeds to be called on eachObject-sized region. This is an important detail: the memory is allocated once, but the constructor is called in 100 locations.When a block is allocated via
malloc, it cannot be freed in pieces. Only a call tofree(block)will release that memory. The C++ keyworddeleteinternally callsfreeif the keywordnewcallsmalloc. So, the proper way to delete an array is to calldelete [] array. So, what happens if you calldelete array? The likely answer is that the memory will be freed (all of it, not just the first element), but only one destructor will be called: the first element’s destructor.Obviously, there are lots of facts to consider.
newanddeleteare not necessarily bound tomallocandfree. They may use system calls unique to a specific architecture or operating system. (Windows, in particular, has a whole set of heap management functions outside ofmallocandfreein its C API.) I simply demonstrated the example withmallocandfreebecause that is what I have seen the most often when stepping through code. Visual Studio, for example, lets you step intonewcalls and actually see thenewfunction code. (That’s another important detail.newanddeleteare simply function calls, which you can even override in many cases.)You can demonstrate this concept with this little program. Simply create an
Objectclass that outputs something during the constructor and outputs something else during the destructor.I ran it, and sure enough: the constructor was called 4 times, and the destructor was called once.