Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Memory and Utilities

Allocation failures and std::bad_alloc in C++

What happens when C++ runs out of memory: std::bad_alloc, bad_array_new_length, nothrow new, set_new_handler, containers and the overcommit caveat.

When new cannot obtain the memory you asked for, it does not return a null pointer. By default it throws std::bad_alloc (declared in <new>). Containers and smart pointers allocate through the same mechanism, so std::vector::push_back, std::string growth and std::make_shared can all throw it.

There are three ways to handle the failure: catch the exception, use the nothrow form of new, or install a new handler that tries to free memory and lets new retry.

C++
try {
    auto big = std::make_unique<char[]>(huge);
} catch (const std::bad_alloc&) { /* recover */ }

Try it

C++ Catching bad_alloc and bad_array_new_length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ nothrow new and a new handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
class bad_alloc : public std::exception { /* what() text is implementation-defined */ };
class bad_array_new_length : public std::bad_alloc {};

void* operator new(std::size_t n);                              // throws bad_alloc
void* operator new(std::size_t n, const std::nothrow_t&) noexcept;   // returns nullptr
new_handler set_new_handler(new_handler h) noexcept;            // returns the previous handler
new_handler get_new_handler() noexcept;
Name Description
bad_alloc Thrown when memory is exhausted.
bad_array_new_length Thrown when the array length is negative or too large to represent. Derives from bad_alloc.
std::nothrow Tag passed to new to request a null result instead of an exception.
new_handler void (*)(). Called repeatedly by new until allocation succeeds.

Errors / undefined behavior: a handler must free memory, install a different handler (or nullptr), or throw bad_alloc/end the program. If it returns without doing one of those and memory is still lacking, new loops forever.

Usage notes

  • Most programs do not recover from bad_alloc. Reasonable policies: catch it at a high level (one request, one job), release a cache, and continue; or let it terminate with a clear message.
  • Be careful in the handler. Do not allocate inside it. Keep a reserve block that you free on the first call.
  • Overcommit: on Linux, new often succeeds for large requests because pages are only committed when touched, and the process is killed later by the OS (out-of-memory killer). A bad_alloc is therefore a poor early-warning signal for moderate sizes. A huge request, like the examples, fails reliably.
  • Containers give a strong guarantee: if push_back throws bad_alloc, the vector is unchanged.
  • std::vector<T>(n) throws std::length_error when n exceeds max_size(), and bad_alloc when the allocation itself fails.
  • noexcept code that allocates calls std::terminate when the allocation throws. Destructors and move operations should therefore not allocate.
  • Use -fno-exceptions builds carefully: there, new aborts instead of throwing.
  • malloc returns NULL; new does not. Never test a plain new result for null. Only the nothrow form can return it.
  • Prefer RAII so a failed allocation halfway through a function does not leak what was allocated before it.