bad_alloc.cc
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 16 Apr 2009 12:49:13 +0200
changeset 59 a7ba10b68915
parent 29 7abf6146898e
child 77 49e0babccb23
permissions -rw-r--r--
getpwnam_error.c: * The memory hole can be fixed with two different approaches 1) Change /etc/nsswitch.conf: passwd: compat to passwd: files 2) LD_PRELOAD=/lib/libnss_compat.so.2 valgrind ./getpwnam_error GLIBC loads libnss_compat on the fly and unloads it. Thanks to telexicon for reporting this... committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * test/demos/bad_alloc.cc
 * Copyright (C) 2008 Markus Broeker
 */

#include <iostream>
#include <vector>
#include <exception>
#include <sys/time.h>
#include <sys/resource.h>
#include <cstdlib>

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.clear ();
        switch (action) {
        case 'y':
            throw;
            break;
        }
    }

    return EXIT_SUCCESS;
}