7

Is the behaviour of this code defined?

int* ptr = new int[10];
operator delete[] (ptr, 0);

This code compiles fine and (on my machine) it seems nothing is happening. Is its the behaviour defined somewhere?

user7769147
  • 1,559
  • 9
  • 15
  • [This `operator delete` and `operator delete[]` reference](https://en.cppreference.com/w/cpp/memory/new/operator_delete) should be helpful. Exact which overload you're calling is hard to say though. – Some programmer dude Jul 26 '19 at 12:32
  • I think it's undefined behaviour. The comma operator evaluates `ptr` and discards the result, then passes `0` (an invalid address) to delete – Tharwen Jul 26 '19 at 12:33
  • 4
    @Tharwen It's a function call. There is no comma operator here. – Rakete1111 Jul 26 '19 at 12:35
  • 2
    @Tharwen 0 is a valid address to delete. It is a null pointer literal. – eerorika Jul 26 '19 at 12:36
  • @Rakete1111 I see that now. How can it take 2 arguments though? – Tharwen Jul 26 '19 at 12:38
  • @eerorika I (mistakenly) thought deleting a null ptr was equivalent to deleting memory that hadn't been allocated with new and therefore undefined – Tharwen Jul 26 '19 at 12:39
  • 1
    @Tharwen They can have 3 arguments even! :) Have a look: https://en.cppreference.com/w/cpp/memory/new/operator_delete – Rakete1111 Jul 26 '19 at 12:39

2 Answers2

0

In this statement

operator delete[] (ptr, 0);

there is called explicitly the deallocation function

void operator delete[](void*, std::size_t) noexcept;

The second parameter in the call that has the type size_t is just set to 0.

The behavior of the call then the second parameter is equal to 0 is undefined provided that when the allocated memory was not have the size equal to 0.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

tl;dr: The behavior might as well be undefined, avoid such a statement.

This answer is aimed at most C++ software developers, not so much at language-lawyer types who want the formal official answer.

The delete[](ptr, 0) call has no strong reason for the standard committee to define behavior for. Also, even if such a behavior were to be defined - there is no single obvious behavior we would expect:

  • It could throw an exception.
  • It could do nothing.
  • It could be the same as delete[](ptr) or delete[](ptr, 10).
  • It could be even be 'defined' as implementation-defined...

It is not a good idea for your code to rely on such a choice, even if the standards committee had made it. It would make your code difficult to understand and easy to break - for somebody else, or even for yourself, a few years down the line.

That's why it doesn't really matter whether the behavior here is defined, and you should absolutely avoid such a statement.

See also :

einpoklum
  • 118,144
  • 57
  • 340
  • 684