Reputation: 668
I am concerned that a C++ program may consume an unacceptably large amount of memory. Rather than rudely gobbling up all possible RAM and swap before going down in flames, I would prefer to have the program limit itself to some maximum amount of heap memory, and have allocations fail when this is exceeded. Ideally, I want to make the maximum heap size a command-line parameter for my program, similar to the -Xmx
option for the Java Virtual Machine. Short of manually bean-counting every little allocation, is there any language feature which could enable this?
Upvotes: 2
Views: 3987
Reputation: 1648
To set stack and heap sizes statically (i.e. at build time) for your executable you can do one of the following depending on your toolchain.
For Visual Studio, setting stack and heap sizes can be done:
/STACK:NNN
and /HEAP:MMM
command-line options where NNN
and MMM
are stack and heap sizes respectively,#pragma comment(linker "/STACK:NNN")
and #pragma comment(linker "/HEAP:MMM")
.Alternatively, you can modify stack and heap sizes of an existing executable using EDITBIN tool.
For gcc, setting stack and heap sizes can be done:
-Wl,--stack=NNN
and -Wl,--heap=MMM
.To set heap size dynamically (i.e. at run time) you can:
In your implementation of the operator/hook, you can limit the heap size (i.e. fail to allocate memory) as you need (e.g. based on a command-line parameter).
Upvotes: 2