2

When combining new[] with delete instead of delete[], what really happens? I tried the following code and found there is no memory leak, so why does delete on a new[] returned pointer not cause a leak?

How does the compiler know the number of bytes to be freed?

int main() {
  constexpr int size = 102400;
  while (1) {
    char* buffer = new char[size]{};
    delete buffer;
  }

  return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
bugs king
  • 566
  • 5
  • 13
  • I am not talking about valgrind here, I wonder if you delete a new[] pointer, how can it figure out the block size to be freed? – bugs king Apr 28 '17 at 07:03
  • Now you have a good question. But extend that a step further: How does it figure out That your allocated array was one element or one million elements? – user4581301 Apr 28 '17 at 07:07
  • The code is not required to work without the `[]`, but it is also not required **not** to work. – Bo Persson Apr 28 '17 at 09:54

2 Answers2

4

Formally the program behaviour is undefined, since you need to match a new[] with a delete[].

But one possible manifestation of the undefined behaviour is for a compiler to "play nice", and do what you intended. (One of the compilers I work with does this and forms part of its documentation.)

But don't rely on that else you're not writing strictly portable C++.

Note also that you may well not observe a memory leak since the C++ runtime library and the operating system might not actually give you the memory until you make use of it. A compiler may even optimise out your loop entirely - as it's a no-op - especially if the memory allocation and deallocation calls were correctly written.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Talking about gcc here, how does it know the actual amount of size to be freed if call delete instead of delete[]? – bugs king Apr 28 '17 at 07:22
  • @bugsking the actual byte size may be stored in a header at the front of the allocated memory. But it is still undefined behavior. And you could get leaks if you create an array of a class type that has a destructor. `delete` would not call all of the array element destructors, whereas `delete[]` would. – Remy Lebeau Apr 28 '17 at 07:42
0

If optimization is turned on, then compiler can remove your while-loop or inside allocation and deallocation of memory. Otherwise as was said, your program has undefined behaviour.

mato7d5
  • 10
  • 1
  • 3