// bad_alloc standard exception
#include <iostream>
#include <exception>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <ctime>

using namespace std;

int main () {
  int* myarray= NULL;
  //std::cout<<"pow(2,30) is  "<<pow(2,30)<<std::endl;
  int e = 20;
  long c = pow(2,e);
  //int e = 0;
  clock_t startt = std::clock();
clock_t endt = std::clock();
  try
  {
    do {
      std::cout<<"c : "<<c<<"\t"<<"e : "<<e <<std::endl;
      myarray= new int[c];
      //std::cout<<"sizeof myarray : "<<sizeof(myarray)<<std::endl;// it will be 8, pointer size
      //
      //sleep(20);

      clock_t tmp_startt = std::clock();
      //clock_t tmp_endt = std::clock();
      //if you use int for i, you will overflow i get a segment fault.
      long i = 0;
      for (; i < c; ++i) {
          //myarray[i] = i;
          *(myarray+i) = i;
      }
      std::cout<<"Assigning took " << ( ( std::clock()- tmp_startt ) / (double)CLOCKS_PER_SEC )<<" seconds."<<std::endl;
    if ( myarray != NULL ) { delete [] myarray; myarray = NULL;}
      c = pow(2,++e);
      std::cout<<std::endl;
    } while (true);

  }
  catch (bad_alloc&)
  {
      cout << "Error allocating memory." << endl;
      std::cout<<"c : "<<c<<"\t"<<"e : "<<e <<std::endl;
      if ( myarray != NULL ) { delete [] myarray; myarray = NULL;}
  }
  catch (exception& e)
  {
    cout << "Standard exception: " << e.what() << endl;
  }
  return 0;
}
	  
	  
	  
	  
	  
