bad_alloc in C++

Last Updated : 20 Jun, 2026

std::bad_alloc is a standard exception class that indicates failure of dynamic memory allocation. It is defined in the <new> header and is automatically thrown by the new operator when it cannot allocate the requested memory.

  • Thrown when the new operator fails to allocate memory.
  • Derived from std::exception and provides the what() member function.

Prerequisite : Exceptions in C++

Example: The following program demonstrates how std::bad_alloc can be caught when a memory allocation request fails.

C++
#include <iostream>
#include <new>

// Driver code
int main () {
  try
  {
     int* gfg_array = new int[100000000];
  }
  catch (std::bad_alloc & ba)
  {
     std::cerr << "bad_alloc caught: " << ba.what();
  }
  return 0;
}

Output

bad_alloc caught: std::bad_alloc

Explanation

  • The new operator attempts to allocate a very large block of memory.
  • If the allocation fails, a std::bad_alloc exception is thrown and handled by the catch block.

Syntax

The std::bad_alloc exception is typically handled using a try-catch block.

try {

// memory allocation

}

catch (const std::bad_alloc& e) {

// handle allocation failure

}

Where:

  • try contains the code that may throw std::bad_alloc.
  • catch handles the exception if memory allocation fails.

Handling Memory Allocation Failure

The new operator throws std::bad_alloc whenever sufficient memory is unavailable. Catching this exception prevents the program from terminating unexpectedly.

  • Allows the program to recover gracefully from allocation failures.
  • Useful for applications that allocate large amounts of dynamic memory.

what() Member Function

The std::bad_alloc class inherits the what() function from std::exception, which returns a description of the exception.

  • Returns an implementation-defined error message.
  • Commonly used inside the catch block for debugging.

Syntax

what()

Return Value

std::bad_alloc

Using new (nothrow)

Instead of throwing an exception, the nothrow version of new returns nullptr when memory allocation fails.

  • Avoids exception handling.
  • The returned pointer must be checked before use.
C++
#include <iostream>
#include <new>
using namespace std;

int main() {
    int* ptr = new (nothrow) int[1000000000000];

    if (ptr == nullptr)
        cout << "Memory allocation failed";

    delete[] ptr;

    return 0;
}

Output
Memory allocation failed

Applications of std::bad_alloc

std::bad_alloc helps programs safely handle memory allocation failures.

  • Prevents unexpected program termination due to failed allocations.
  • Used in memory-intensive applications to implement recovery mechanisms.
Comment