Artificially Limit C/C++ Memory Usage

Viewed 7493

Is there any way to easily limit a C/C++ application to a specified amount of memory (30 mb or so)? Eg: if my application tries to complete load a 50mb file into memory it will die/print a message and quit/etc.

Admittedly I can just constantly check the memory usage for the application, but it would be a bit easier if it would just die with an error if I went above.

Any ideas?

Platform isn't a big issue, windows/linux/whatever compiler.

5 Answers

You can limit the size of the virtual memory of your process using the system limits. If you process exceeds this amount, it will be killed with a signal (SIGBUS I think).

You can use something like:

#include <sys/resource.h>
#include <iostream>

using namespace std;

class RLimit {
public:
    RLimit(int cmd) : mCmd(cmd) {
    }

    void set(rlim_t value) {
        clog << "Setting " << mCmd << " to " << value << endl;
        struct rlimit rlim;
        rlim.rlim_cur = value;
        rlim.rlim_max = value;
        int ret = setrlimit(mCmd, &rlim);
        if (ret) {
            clog << "Error setting rlimit" << endl;
        }
    }

    rlim_t getCurrent() {
        struct rlimit rlim = {0, 0};
        if (getrlimit(mCmd, &rlim)) {
            clog << "Error in getrlimit" << endl;
            return 0;
        }
        return rlim.rlim_cur;
    }
    rlim_t getMax() {
        struct rlimit rlim = {0, 0};
        if (getrlimit(mCmd, &rlim)) {
            clog << "Error in getrlimit" << endl;
            return 0;
        }
        return rlim.rlim_max;
    }

private:
    int mCmd;
};

And then use it like that:

RLimit dataLimit(RLIMIT_DATA);
dataLimit.set(128 * 1024 );  // in kB
clog << "soft: " << dataLimit.getCurrent() << " hard: " << dataLimit.getMax() << endl;

This implementation seems a bit verbose but it lets you easily and cleanly set different limits (see ulimit -a).

Related