Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Artificially Limit C/C++ Memory Usage

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.

like image 797
Paul Avatar asked Sep 23 '10 01:09

Paul


People also ask

How do you set a memory limit in C++?

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.

Does C use less memory than C++?

There is no real difference between C and C++ in terms of memory allocation.

How do you get exhaust memory?

To simply exhaust memory, you don't need that at all. You can call new int(i) and throw away the returned pointer, and the memory will still be allocated. Remember also that your machine likely has virtual memory beyond the 2 GB physical RAM you have installed.


2 Answers

Read the manual page for ulimit on unix systems. There is a shell builtin you can invoke before launching your executable or (in section 3 of the manual) an API call of the same name.

like image 96
dmckee --- ex-moderator kitten Avatar answered Sep 19 '22 15:09

dmckee --- ex-moderator kitten


On Windows, you can't set a quota for memory usage of a process directly. You can, however, create a Windows job object, set the quota for the job object, and then assign the process to that job object.

like image 44
Jerry Coffin Avatar answered Sep 21 '22 15:09

Jerry Coffin