2

Hello I have a simple example: Since C++ allows a 0-size dynamic array of type T then how can I free it?

a = new int[0];
delete[] a;// UB?

As you can see above C++ compiler doesn't now about dynamic arrays size so it can be 0 so the code works. I also know that this array a works as past-end pointer so it cannot be neither de-referenced nor incremented/decremented.

  • I don't know what happens behind the curtain in operator new in this case? Does it allocate memory or not? or does it fail?

  • If I don't free this memory using delete[] a; is it a memory leak?

  • Can assign to it like: a = new int[10];?

Maestro
  • 2,512
  • 9
  • 24
  • Subvert the problem. `std::vector`. Now you have a zero size "array", and when it goes out of scope it will be handled automagically. `new` is now the *new* `goto`. You really shouldn't use it. – NathanOliver Feb 27 '20 at 20:49
  • This can be tested. run `while(true) new int[0]` and check the memory profile. – andre Feb 27 '20 at 20:49
  • 2
    Yes you need to free the memory with `delete[] a;`. You are allowed to read the pointer `a` but must not *deference* it. An interesting question is whether or not you are allowed to read the pointer `a + 1`. I don't *think* you are allowed to. Another interesting question is is the compiler allowed to set `a` to `nullptr`? I don't think it is. – Bathsheba Feb 27 '20 at 21:39
  • 2
    I've asked the community on the points I've raised in the comment above. See https://stackoverflow.com/questions/60442205/properties-of-a-pointer-to-a-zero-length-array. – Bathsheba Feb 27 '20 at 21:48

0 Answers0