2

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?

feersum
  • 658
  • 4
  • 11
  • 1
    Do the algorithms being executed justify the memory expense? – Robert Harvey Feb 22 '15 at 01:32
  • There's [this stackoverflow question](http://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process) – motoku Feb 22 '15 at 01:34
  • 2
    You can replace the global new operator with your own – quantdev Feb 22 '15 at 01:36
  • There's no such standard C++ feature(bar tracking all memory allocations done yourself), but there are probably system specific features that will allow you to control that, such as [ulimit](http://superuser.com/questions/220059/what-parameters-has-ulimit) So tell us about your platform. – nos Feb 22 '15 at 01:39
  • 1
    Overriding global `new` sounds like the kind of hack I would be interested in ;) – feersum Feb 22 '15 at 01:40
  • @nos I'm currently on Windows, but would prefer to have the most broadly applicable solution. – feersum Feb 22 '15 at 01:46
  • This might be a duplicate of http://stackoverflow.com/q/14144168/103167 or http://stackoverflow.com/q/192876/103167 – Ben Voigt Feb 22 '15 at 01:55

1 Answers1

2

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).

Petr Vepřek
  • 1,547
  • 2
  • 24
  • 35