Skip to content
Related Articles

Related Articles

Improve Article

bad_alloc in C++

  • Difficulty Level : Medium
  • Last Updated : 27 Feb, 2018

Prerequisite : Exceptions in C++

Standard C++ contains several built-in exception classes. The most commonly used is bad_alloc, which is thrown if an error occurs when attempting to allocate memory with new.

This class is derived from exception.

To make use of bad_alloc, one should set up the appropriate try and catch blocks. Here’s a short example, that shows how it’s used :

C++




// CPP code for bad_alloc
#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;
}


RunTime error :
bad_alloc caught: std::bad_alloc
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :