2

Is the following code undefined behavior according to the C++ standard? Please share C++ standard references.

void* operator new(std::size_t sz)
{
    return ::new int(5);
}
Ionut Alexandru
  • 680
  • 5
  • 17
  • Follow these links [(1) Stack overflow answer](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a) and [(2) cppreference.com](https://en.cppreference.com/w/cpp/language/ub). I hope this helps! Cheers – Yiğit Aras Tunalı Nov 13 '19 at 23:16

1 Answers1

4

6.7.5.4.11 specifically talks about the requirements on allocation functions. It lays out all the requirements that such a function must meet, and doesn't explicitly forbid calling the global allocation function.

It does say this:

If it is successful, it returns the address of the start of a block of storage whose length in bytes is at least as large as the requested size.

Your function always returns a block of size equal to sizeof(int).

6.7.5.4 Also says this

If the behavior of an allocation or deallocation function does not satisfy the semantic constraints specified in [basic.stc.dynamic.allocation] and [basic.stc.dynamic.deallocation], the behavior is undefined.

The previous version of this answer missed that point. Your function doesn't return a memory block that is equal in size to the requested size (which is ignored), so the behavior is undefined.


1 On this site.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135