How can we get this information? I guess it is OS dependent, and I’m running Windows so my question refers to the windows API.
Is there any function that can do that for us – get the remaining stack memory for the calling thread?
Alternatively, if we could find out the following details, we will be able to calculate that on our own:
- Get the thread stack base address. There must be some function that takes a thread identifier as a parameter, and returns some information about it (Such as… Stack base address?)
- Get the thread stack size. If the thread was started by us, we can know it (Since we specified it when calling
CreateThread). But if it is the main thread, which was started by the OS for our program, or any other thread we did not start explicitly, how do we find it? - Get the current stack pointer. Well, that’s easier. we can either check it with
esp, or take the address of a local variable, to get a close location.
This is for educational purposes, but I guess it could be used to stop a recursive algorithm from causing a stack overflow – Instead of using any max-depth limiting function.
You can use NtCurrentTeb(), which gets you a pointer to the TEB. This has NT_TIB as its first member: