I would like to know if there is a way to programmatically determine the stack size of a running program in C++. If so, is there also a way to programatically determine how much heap memory the program is using at run time? For determining the size of the heap, I could see a potential way by overloading the new
and delete
operator, but I don't think this would work with smart pointers.
I tried to achieve it with the following:
int main(){
const char STACK_BEGIN = 'A';
//a lot of code
register unsigned long int STACK_NOW asm("%esp");
long long int stack_size = (reinterpret_cast<int>(&STACK_BEGIN) - STACK_NOW);
//rest of code
}
I approximately solved it like this:
int main(){
const char STACK_BEGIN = 'A'; //a lot of code
register unsigned long int STACK_NOW asm("%esp");
long long int stack_size = (reinterpret_cast<int>(&STACK_BEGIN) - STACK_NOW); //rest of code
}
First of all, the stack is an attribute of a thread, each thread has it's own stack.
As threads are provided by the platform, the system interface may or may not provide the information.
For Linux this is function pthread_attr_getstacksize()
.
If in addition you want to get the actual address range, you get this from STACK_BEGIN and the processor architectural convention, that stacks are top-down, i.e. STACK_BEGIN is actually at the top and the bottom is about at STACK_BEGIN-´size of the stack´
.
For Windows the stack range is hidden in GetThreadInformation(()
, see processhacker
EDIT According to comment from Raymond Chen GetCurrentThreadStackLimits is the documented choice inside Windows SDK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With