# HG changeset patch # User Markus Bröker # Date 1229187473 -3600 # Node ID 97beb75e5ac7809a911f24bc5265c519444e0346 # Parent 6b13c229a60f72032e07577d8eded620581e4941 bad alloc example added committer: Markus Bröker diff --git a/Makefile b/Makefile --- 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: diff --git a/bad_alloc.cc b/bad_alloc.cc new file mode 100644 --- /dev/null +++ b/bad_alloc.cc @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include + +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; +}