Mega Code Archive

 
Categories / C++ Tutorial / Exceptions
 

Demonstrating standard new throwing bad_alloc when memory cannot be allocated

#include <iostream> using std::cerr; using std::cout; using std::endl; #include <new> using std::bad_alloc;                   int main() {    double *ptr[ 50 ];        try     {       for ( int i = 0; i < 50; i++ )        {          ptr[ i ] = new double[ 50000000 ];          cout << "Allocated 50000000 doubles in ptr[ " << i << " ]\n";       }    }catch ( bad_alloc &memoryAllocationException )    {       cerr << "Exception occurred: " << memoryAllocationException.what() << endl;    }        return 0; } Allocated 50000000 doubles in ptr[ 0 ] Allocated 50000000 doubles in ptr[ 1 ] Allocated 50000000 doubles in ptr[ 2 ] Allocated 50000000 doubles in ptr[ 3 ] Allocated 50000000 doubles in ptr[ 4 ] Exception occurred: St9bad_alloc