Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining stack size at runtime in a C++ Program

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
}
like image 284
Exagon Avatar asked Mar 28 '16 13:03

Exagon


2 Answers

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 
}
like image 107
Exagon Avatar answered Oct 21 '22 13:10

Exagon


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.

like image 27
Sam Ginrich Avatar answered Oct 21 '22 13:10

Sam Ginrich