Determining stack size at runtime in a C++ Program

2019-05-10 22:31发布

问题:

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
}

回答1:

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 
}