Stack and Heap Space in Modern Computers – C Guide

c++heap-memorymemory-managementstack-memory

When writing in C, how can I tell how much stack space is available in memory when I launch a program? How about heap space?

How can I tell how much memory is being used during the execution of my program?

Best Answer

This is all Win32-specific (not really C-specific, all just OS API):

When a thread is created, it gets 1MB stack space by default, by that can be modified in whatever CreateThread API you use.

You can peek into the thread information block to find the actual stack info, but even though this is documented, this technique isn't officially supported, see http://en.wikipedia.org/wiki/Win32_Thread_Information_Block .

Also, for a 32-bit application, you can only address up to 2GB, so for an app that by design uses lots of memory, then the thing to watch out for is the total size of the process' virtual address space (committed + reserved), which includes all heap allocations. You can programmatically access the process' virtual memory with the GlobalMemoryStatusEx API, look at the ullTotalVirtual param for virtual address space. Once your process gets close to 1.8 or 1.9GB of VAS, then heap allocations and VirtualAlloc calls begin to fail. For "normal" apps, you don't have to worry about running out of VAS, but it's always good to check for fail allocs. Also, you shouldn't get a stack overflow, unless you have a bug, or a bad design.

Related Question