c++windowsmultithreadingstack-overflowstack-size

Can I ask a running thread about how much stack it has been using?


So let's say I have created a thread, on Windows OS, for which I know that the default stack size is much more than what is needed. Can I then run the application and ask the thread about the amount of stack it actually has used so that I know how much I should set its stack size instead of the default stack size?


Solution

  • Windows usually doesn't commit the entire stack, it only reserves it. (Well, unless you ask it to, e.g. by specifying a non-zero stack size argument for CreateThread without also passing the STACK_SIZE_PARAM_IS_A_RESERVATION flag).

    You can use this to figure out how much stack your thread has ever needed while running, including any CRT, WinAPI or third-party library calls.

    To do that, simply read the StackBase and StackLimit values from the TEB - see answers to this question for how to do that. The difference of the two values should be the amount of stack memory that has been committed, i.e. - the amount of stack memory that the thread has actually used.

    Alternatively, if a manual process is sufficient: Simply start the application in WinDBG, set a breakpoint before the thread exits and then dump the TEB with the !teb command. You can also dump the entire memory map with !address and look for committed areas with usage Stack.