Search code examples
c++stackstack-overflowvisual-studio-debugging

How do i find out the size of available stack space?


We all know that stack is growing downward, so it's really a straightforward assumption that if we find the address of the last declared variable, we will get out the smallest address in stack, so we could just assume that this address will be our residual available stack.

And i did it, and i got just humongous address {0x000000dc9354f540} = {947364623680} we know that stack growing downward and we know that we can't go lower than 0. so a bit of math:

947364623680 / (1024*1024*1024) = 882.302060425

--> Do they imply that i have 882Gb of stack on my machine?!

I test it and obviously get the stack overflow exception after allocating additional 2mb on stack:

uint8 array[1024*1024*2] = {};

And there my question come WTF is this, and how can i get my actual stack size?


Solution

  • Since you question has a tag "visual-studio-debugging" I assume you use windows.

    First you should get the current stack pointer. Either get an address of a local dummy variable (like you did now), or by raw asm read esp/rsp, or get an address of a local dummy variable (like you did now), or get CPU register via Win32 API call to GetThreadContext).

    Now, in order to find out the available stack size you may use VirtualQuery to see the starting address of this virtual memory region (aka allocation base address). Basically subtracting those pointers would give you the remaining stack size (precision up to the size of the current stack frame).

    Long time ago I've written an article about this subject, including querying the currently allocated/reserved stack size. You can find out more info there if you want:

    Do they imply that i have 882Gb of stack on my machine?!

    It has nothing to do with the "stack on your machine". It's about virtual address space, which has nothing to do with the physical storage (RAM + page files) available in the system.