This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 108i. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2022-07-16


624. Overflow in calculating size of allocation

Section: 7.6.2.8  [expr.new]     Status: CD1     Submitter: Jens Maurer     Date: 8 March 2007

[Voted into the WP at the September, 2008 meeting (resolution in paper N2757).]

Issue 256 was closed without action, principally on the the grounds that an implementation could provide a means (command-line option, #pragma, etc.) for requesting that the allocation size be checked for validity, but that “it would not be appropriate to require this overhead for every array allocation in every program.”

This rationale may be giving too much weight to the overhead such a check would add, especially when compared to the likely cost of actually doing the storage allocation. In particular, the test essentially amounts to something like

    if (max_allocation_size / sizeof(T) < num_elements)
        throw std::bad_alloc();

(noting that max_allocation_size/sizeof(T) is a compile-time constant). It might make more sense to turn the rationale around and require the check, assuming that implementations could provide a mechanism for suppressing it if needed.

Suggested resolution:

In 7.6.2.8 [expr.new] paragraph 7, add the following words before the example:

If the value of the expression is such that the size of the allocated object would exceed the implementation-defined limit, an exception of type std::bad_alloc is thrown and no storage is obtained.

Note (March, 2008):

The Evolution Working Group has accepted the intent of issue 256 and referred it to CWG for action for C++0x (see paper J16/07-0033 = WG21 N2173).

Proposed resolution (March, 2008):

As suggested.

Notes from the June, 2008 meeting:

The CWG felt that this situation should not be treated like an out-of-memory situation and thus an exception of type std::bad_alloc (or, alternatively, returning a null pointer for a throw() allocator) would not be appropriate.

Proposed resolution (June, 2008):

Change 7.6.2.8 [expr.new] paragraph 8 as follows:

If the value of the expression in a direct-new-declarator is such that the size of the allocated object would exceed the implementation-defined limit, no storage is obtained and the new-expression terminates by throwing an exception of a type that would match a handler (14.4 [except.handle]) of type std::length_error (19.2.6 [length.error]). Otherwise, if When the value of the that expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

[Drafting note: std::length_error is thrown by std::string and std::vector and thus appears to be the right choice for the exception to be thrown here.]