Search code examples
c++new-operator

Calling the new expression in an overload of operator new


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);
}

Solution

  • 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.