bad_alloc.cc
changeset 2 97beb75e5ac7
child 8 96d16dfe787a
equal deleted inserted replaced
1:6b13c229a60f 2:97beb75e5ac7
       
     1 #include <iostream>
       
     2 #include <vector>
       
     3 #include <exception>
       
     4 #include <sys/time.h>
       
     5 #include <sys/resource.h>
       
     6 
       
     7 using namespace std;
       
     8 
       
     9 int set_limit (int megs)
       
    10 {
       
    11     struct rlimit rlim;
       
    12 
       
    13     rlim.rlim_cur = megs;
       
    14     rlim.rlim_max = 1.25 * megs;
       
    15     if (megs > (4 * 1024 * 1024))
       
    16         return setrlimit (RLIMIT_AS, &rlim);
       
    17     return EXIT_FAILURE;
       
    18 }
       
    19 
       
    20 int main (int argc, char **argv)
       
    21 {
       
    22     vector < int >v;
       
    23     int i = 0;
       
    24     char action;
       
    25 
       
    26     if (set_limit (20 * 1024 * 1024)) {
       
    27         cout << "System error" << endl;
       
    28         return EXIT_FAILURE;
       
    29     }
       
    30 
       
    31     try {
       
    32         for (;;) {
       
    33             v.push_back (i++);
       
    34         }
       
    35     }
       
    36     catch (exception & e) {
       
    37         cout << e.what () << " after " << i << " iterations" << endl << endl;
       
    38         cout << "Would you like to see the full error message? (y/n) ";
       
    39         cin >> action;
       
    40 		v.resize(0);
       
    41         switch (action) {
       
    42         case 'y':
       
    43             throw;
       
    44             break;
       
    45         }
       
    46     }
       
    47 
       
    48     return EXIT_SUCCESS;
       
    49 }