# C++: terminate called after throwing an instance of 'std::bad_alloc' — what(): std::bad_alloc

**Code:** `std::bad_alloc` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

`new` or a container could not get the memory requested — either the system is out of memory or the size was absurdly large (often a negative or uninitialised value).

## Meaning

A bad_alloc is thrown by `operator new` when allocation fails. Many cases are not a real shortage: an `int` size that became huge after a signed/unsigned conversion, an uninitialised variable passed to `std::vector(n)`, or an infinite loop adding elements. Also check limits like `ulimit -v`, container memory limits, and 32-bit address space.

## Common causes

- Size computed from an uninitialised or negative number (converted to a huge `size_t`)
- Real memory exhaustion: unbounded growth, leaks
- Container or `ulimit -v` memory limit (Docker, cgroups)
- 32-bit build hitting the 2–4 GB address-space limit
- `new` of an enormous array

## Quick fix

1. Print the requested size before allocating and validate it
2. Catch `std::bad_alloc` where you can degrade gracefully
3. Check `free -h`, `ulimit -a` and container limits

## Detailed fix by platform

### Linux

1. `ulimit -v` (address-space limit) and `free -h`; in Docker check `docker stats` and the `--memory` setting
2. Run under valgrind or AddressSanitizer to find leaks

### C++

1. Validate input sizes; use `reserve()` carefully and prefer streaming over loading whole files

## Code examples

### Guard the size

```cpp
#include <vector>
#include <new>
#include <iostream>

int main(int argc, char** argv) {
    long long n = argc > 1 ? std::atoll(argv[1]) : -1;     // -1 becomes a huge size_t below
    if (n < 0 || n > 100'000'000) { std::cerr << "bad size\n"; return 1; }
    try {
        std::vector<int> v(static_cast<std::size_t>(n));
    } catch (const std::bad_alloc& e) {
        std::cerr << "out of memory: " << e.what() << "\n";
    }
}
```

## How to diagnose

1. **Size** — What size was requested?
2. **Memory** — Free memory and limits?
3. **Growth** — Does memory keep growing (leak)?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/std-bad-alloc)
