views:

188

answers:

4

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.

+2  A: 

Override all malloc APIs, and provide handlers for new/delete, so that you can book keep the memory usage and throw exceptions when needed.

Not sure if this is even easier/effort-saving than just do memory monitoring through OS-provided APIs.

Arthur
I would do that :) (it's enough to hook the HeapAlloc() win32 API)
ruslik
+6  A: 

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.

dmckee
Note that the `ulimit()` API is obsolete. You want `setrlimit()` instead.
bstpierre
@bstpierre: The man page on my Mac OS 10.5 box doesn't mention anything about that (though `setrlimit (2)` is also present and postdates `ulimit (3)`). Do you know what standards make the change?
dmckee
@dmckee: Man page on my linux box says: `CONFORMING TO SVr4, POSIX.1-2001. POSIX.1-2008 marks ulimit() as obsolete.` See the note on the [online man page](http://www.opengroup.org/onlinepubs/9699919799/functions/ulimit.html#tag_16_630_13).
bstpierre
+4  A: 

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.

Jerry Coffin
+6  A: 

In bash, use the ulimit builtin:

bash$ ulimit -v 30000
bash$ ./my_program

The -v takes 1K blocks.

Update:

If you want to set this from within your app, use setrlimit. Note that the man page for ulimit(3) explicitly says that it is obsolete.

bstpierre