feersum
feersum

Reputation: 668

Self-limit heap size in C++

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

Answers (1)

Petr Vepřek
Petr Vepřek

Reputation: 1648

Static stack and heap sizes

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:

  • using /STACK:NNN and /HEAP:MMM command-line options where NNN and MMM are stack and heap sizes respectively,
  • via GUI (project properties --> configuration properties --> linker --> system...), or
  • using pragma directive e.g. #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:

  • using command line options -Wl,--stack=NNN and -Wl,--heap=MMM.

Dynamic heap size

To set heap size dynamically (i.e. at run time) you can:

  • overload C++ operators new and delete (malloc and free in C) or
  • use an allocation hook on your platform (e.g. _CrtSetAllocHook for MS CRT).

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

Related Questions