bad alloc example added
authorMarkus Bröker <mbroeker@largo.dyndns.tv>
Sat, 13 Dec 2008 17:57:53 +0100
changeset 2 97beb75e5ac7
parent 1 6b13c229a60f
child 3 820ed7fb9314
bad alloc example added committer: Markus Bröker <mbroeker@largo.homelinux.org>
Makefile
bad_alloc.cc
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
 CC=gcc -g -ggdb
+CPP=g++ -g -ggdb
 CFLAGS=-Wall -O2 -Iinclude -ansi
-NASM=nasm -f elf -Iinclude/
 TARGET=ncurses \
 	numerierung \
 	xdemo \
@@ -32,14 +32,19 @@
 	varargs \
 	concatenation \
 	alpha_beta \
-	life
+	life \
+	bad_alloc
 
-.SUFFIXES: .c .asm
+.SUFFIXES: .c .cc .asm
 
 .c.o:
 	@echo Compiling $< ...
 	@$(CC) -c $(CFLAGS) -o $@ $<
 
+.cc.o:
+	@echo Compiling $< ...
+	@$(CPP) -c $(CFLAGS) -o $@ $<
+
 .asm.o:
 	@echo Assembling $< ...
 	@$(NASM) $< -o $@
@@ -170,10 +175,14 @@
 	@echo Linking $< ...
 	@$(CC) -o $@ $<
 
-life: life.c
+life: life.o
 	@echo Linking $< ...
 	@$(CC) -o $@ $<
 
+bad_alloc: bad_alloc.o
+	@echo Linking $< ...
+	@$(CPP) -o $@ $<
+
 .PHONY: clean uninstall
 
 clean:
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;
+}