1

I'm writing some memory management code in C++, and at first I use char *ptr = new char[1024] instead of void *malloc(unsigned int size) to get a buffer, after this, there's no concept of array in my code, all the operation is done by pointers.

But when I want to free them, I got some worries. As far as I know, C++ asked programmers to use delete[] when acquire memory by using new *type*[], but at this moment I only got a pointer (which is ptr in the case above). Before coding this I think why using delete[] is to call the destructors on each element. But I'm not sure if there's a difference between delete and delete[] on a pod array.

So is it safe to use delete ptr on a pod array?

Oblivion
  • 7,176
  • 2
  • 14
  • 33
  • 5
    Matching `new[]` with plain `delete` leads to *undefined behavior*, end of story. Just don't do such things. – Some programmer dude Dec 03 '19 at 07:09
  • @Someprogrammerdude Concise, thanks. –  Dec 03 '19 at 07:10
  • 1
    I'm sorry for maybe sounding a little rude, but there's really not much more to say :) – Some programmer dude Dec 03 '19 at 07:16
  • 1
    It is not safe. Possible duplicate of [delete vs delete\[\] operators in C++](https://stackoverflow.com/q/2425728/608639), [The difference between delete and delete\[\] in C++](https://stackoverflow.com/q/4670782/608639), etc. For a concrete example of the problem, see Raymond Chen's [Mismatching scalar and vector new and delete](https://devblogs.microsoft.com/oldnewthing/?p=40763). – jww Dec 03 '19 at 07:47

1 Answers1

3

new comes with delete. new [] comes with delete []. You have no other option:

Called by delete-expressions to deallocate storage previously allocated for a single object. The behavior of the standard library implementation of this function is undefined unless ptr is a null pointer or is a pointer previously obtained from the standard library implementation of operator new(size_t) or operator new(size_t, std::nothrow_t).

Mixing these operators results in undefined behavior.

Oblivion
  • 7,176
  • 2
  • 14
  • 33