newexcp.cpp 694 B

1234567891011121314151617181920212223242526272829303132
  1. // newexcp.cpp -- the bad_alloc exception
  2. #include <iostream>
  3. #include <new>
  4. #include <cstdlib> // for exit(), EXIT_FAILURE
  5. using namespace std;
  6. struct Big
  7. {
  8. double stuff[20000];
  9. };
  10. int main()
  11. {
  12. Big * pb;
  13. try {
  14. cout << "Trying to get a big block of memory:\n";
  15. pb = new Big[10000]; // 1,600,000,000 bytes
  16. cout << "Got past the new request:\n";
  17. }
  18. catch (bad_alloc & ba)
  19. {
  20. cout << "Caught the exception!\n";
  21. cout << ba.what() << endl;
  22. exit(EXIT_FAILURE);
  23. }
  24. cout << "Memory successfully allocated\n";
  25. pb[0].stuff[0] = 4;
  26. cout << pb[0].stuff[0] << endl;
  27. delete [] pb;
  28. // cin.get();
  29. return 0;
  30. }