Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::bad_alloc — allocation failure exception

std::bad_alloc from <new> reports failure to allocate storage. Learn how to catch it by const reference, why what() has no portable fixed text, and how throwing allocation differs from std::nothrow.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <new>

try {
    // Operation that may fail to allocate storage.
} catch (const std::bad_alloc& e) {
    // Handle allocation failure.
}

// C++23 member signature:
// const char* what() const noexcept override;

std::bad_alloc, declared in <new>, is an exception class publicly derived from std::exception. The implementation uses it to report failure to allocate storage. After an unsuccessful attempt, the standard throwing operator new calls the installed new_handler; if none is installed, it throws std::bad_alloc. Returning from the handler causes another attempt.

Catch the exception as const std::bad_alloc&. Its what() member returns an implementation-defined null-terminated description, so do not compare it with fixed text in tests. A handler should avoid unnecessary allocations: another attempt can fail too.

The standard allocation function selected by new (std::nothrow) T returns nullptr on failure instead of reporting allocation failure with an exception. This does not make the entire expression non-throwing: the constructor of T can still throw.

The example deliberately executes throw std::bad_alloc{} rather than attempting to exhaust memory. It tests exception handling, not a real allocator failure. This entry targets C++23; the current working draft may contain later additions, including constexpr for what(), that must not be assumed in C++23.

Examples

#include <cstdio>
#include <new>

int main() {
    try {
        throw std::bad_alloc{};
    } catch (const std::bad_alloc&) {
        std::puts("Allocation failure caught");
    }
}

Result

Allocation failure caught

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources