0

Is there a way to obtain the remaining free stack / heap memory in C# using only managed code?

To be specific, I do not mean the memory that is still available in the currently allocated state but all the memory that (in the future) could be allocated (if necessary) based on the main memory of the host system.

The information will be used to take measures on systems with low free memory to prevent running out of system memory.

ares_games
  • 1,019
  • 2
  • 15
  • 32
  • 1
    The answer to "how long before I hit OOME?" will be different dependent on the size of allocation you try to make. Memory is reserved in contiguous blocks, meaning that you might only be able to reserve considerably less that the total available, especially if you are allocating large arrays or similar. – spender Jan 10 '13 at 00:51
  • Thank you for pointing that out! To make my question more clear: I do only need a rough approximation of free memory e.g. to determine whether <100MB or >300MB of the memory are still available (a precision of ~100MB would suffice). – ares_games Jan 10 '13 at 01:01
  • 1
    Side note: depending if you interested in continuous block or not you may need to do more than just size of free space (see my answer). – Alexei Levenkov Jan 10 '13 at 01:51

2 Answers2

2

There is a method called virtualquery that can be used to determine the size of the call stack. There are a bunch of C# examples here.

Checking available stack size in C

Checking stack size in C#

For big heap allocations you could try the MemoryFailPoint which checks to see if allocation is possible and throws a different exception then OOM http://msdn.microsoft.com/en-us/library/system.runtime.memoryfailpoint.aspx

Community
  • 1
  • 1
AbdElRaheim
  • 1,384
  • 6
  • 8
1

Answer mainly covered by AbdElRaheim... additional note about heap for 32bit systems.

If you want to go all the way with checking space for heap allocations (BTW, somewhat interesting for non-x64 programs): you need not only total amount of free memory but also map of all regions and see what is already allocated. Most interesting piece of information you would be looking for is DLLs loaded into your address space - even having 1GB free does not mean you can allocate 1GB block - there could be multiple chunks that GC can't combine together if some random native DLL is loaded in the middle.

If you want to go that far - VirtualQuery is a possible starting point.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179