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.
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.
There is no real difference between C and C++ in terms of memory allocation.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With