bad_alloc.cc
changeset 2 97beb75e5ac7
child 8 96d16dfe787a
new file mode 100644
--- /dev/null
+++ b/bad_alloc.cc
@@ -0,0 +1,49 @@
+#include <iostream>
+#include <vector>
+#include <exception>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+using namespace std;
+
+int set_limit (int megs)
+{
+    struct rlimit rlim;
+
+    rlim.rlim_cur = megs;
+    rlim.rlim_max = 1.25 * megs;
+    if (megs > (4 * 1024 * 1024))
+        return setrlimit (RLIMIT_AS, &rlim);
+    return EXIT_FAILURE;
+}
+
+int main (int argc, char **argv)
+{
+    vector < int >v;
+    int i = 0;
+    char action;
+
+    if (set_limit (20 * 1024 * 1024)) {
+        cout << "System error" << endl;
+        return EXIT_FAILURE;
+    }
+
+    try {
+        for (;;) {
+            v.push_back (i++);
+        }
+    }
+    catch (exception & e) {
+        cout << e.what () << " after " << i << " iterations" << endl << endl;
+        cout << "Would you like to see the full error message? (y/n) ";
+        cin >> action;
+		v.resize(0);
+        switch (action) {
+        case 'y':
+            throw;
+            break;
+        }
+    }
+
+    return EXIT_SUCCESS;
+}