0

The general equivalence of delete and delete[] has been asked and answered several times. However, I am wondering about a special instance of an array of one element, is it equivalent to a single element?

Should all four of the following two code samples be equivalent?

char * ch = new char;
delete ch;

char * ch = new char;
delete[] ch;

char * ch = new char[1];
delete ch;

char * ch = new char [1];
delete[] ch;
Indinfer
  • 101
  • 8
  • 4
    `delete[]` must be used for `new[]`, and `delete` must be used for `new`, any other combination is undefined behaviour. – dreamlax Mar 07 '16 at 02:47
  • I think I am asking a little different. It is more like, is an array of one element the same as a single element as far as new, new[], delete, and delete[] are concerned? The other questions and answers seem to me to be more general. – Indinfer Mar 07 '16 at 03:02
  • Here is how the compiler responds to undefined behavior; It understands English, Spanish, French, & German. Let's pass it some Chinese, it could spit back to you some form of unrecognizable Greek. – Francis Cugler Mar 07 '16 at 04:43
  • 1
    "*is an array of one element the same as a single element as far as new, new[], delete, and delete[] are concerned*" - NO! `new` is a single object, `new[]` is an array, regardless of its element count. `new[]` typically allocates additional tracking data that `delete[]` uses to know how many elements to destroy before deallocating the array memory. That tracking data is not typically allocated by `new` or used by `delete`. It is possible that any particular implementation might treat `new` as if `new[1]` were called, but that would be an implementation detail, not dictated by the standard. – Remy Lebeau Mar 07 '16 at 19:57
  • 2
    You *must* treat `new`/`delete` and `new[]`/`delete[]` separately and properly to avoid any memory issues. – Remy Lebeau Mar 07 '16 at 19:58
  • I think the responses are correct. But I think I did not express my real question. I posted a different version of my question here: http://stackoverflow.com/questions/35871758/c-is-pointer-to-variable-the-same-as-a-pointer-to-an-array-of-one-element-or. And I might be understanding, but appreciate being able to check my understanding with others. – Indinfer Mar 08 '16 at 15:45

0 Answers0