First page Back Continue Last page Graphics

fig13_05.cpp (1 of 2)

  • 1 // Fig. 13.5: fig13_05.cpp
  • 2 // Demonstrating standard new throwing bad_alloc when memory
  • 3 // cannot be allocated.
  • 4 #include <iostream>
  • 5
  • 6 using std::cout;
  • 7 using std::endl;
  • 8
  • 9 #include <new> // standard operator new
  • 10
  • 11 using std::bad_alloc;
  • 12
  • 13 int main()
  • 14 {
  • 15 double *ptr[ 50 ];
  • 16
  • 17 // attempt to allocate memory
  • 18 try {
  • 19
  • 20 // allocate memory for ptr[ i ]; new throws bad_alloc
  • 21 // on failure
  • 22 for ( int i = 0; i < 50; i++ ) {
  • 23 ptr[ i ] = new double[ 5000000 ];
  • 24 cout << "Allocated 5000000 doubles in ptr[ "
  • 25 << i << " ]\n";
  • 26 }
  • 27
  • 28 } // end try