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.
try { auto big = std::make_unique<char[]>(huge); } catch (const std::bad_alloc&) { /* recover */ }
Try it
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.
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
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,
newoften succeeds for large requests because pages are only committed when touched, and the process is killed later by the OS (out-of-memory killer). Abad_allocis therefore a poor early-warning signal for moderate sizes. A huge request, like the examples, fails reliably. - Containers give a strong guarantee: if
push_backthrowsbad_alloc, the vector is unchanged. std::vector<T>(n)throwsstd::length_errorwhennexceedsmax_size(), andbad_allocwhen the allocation itself fails.noexceptcode that allocates callsstd::terminatewhen the allocation throws. Destructors and move operations should therefore not allocate.- Use
-fno-exceptionsbuilds carefully: there,newaborts instead of throwing. mallocreturnsNULL;newdoes not. Never test a plainnewresult for null. Only thenothrowform can return it.- Prefer RAII so a failed allocation halfway through a function does not leak what was allocated before it.