How to know how much stack function is consuming?

后端 未结 4 1675
天涯浪人
天涯浪人 2021-01-22 06:04

Recently, I came across this question in an interview:
How can we determine how much storage on the stack a particular function is consuming?

4条回答
  •  天涯浪人
    2021-01-22 06:36

    It's completely implementation defined - the standard does not in any way impose requirements on the possible underlying mechanisms used by a program.

    On a x86 machine, one stack frame consists of a return address (4/8 byte), parameters and local variables.

    The parameters, if e.g. scalars, may be passed through registers, so we can't say for sure whether they contribute to the storage taken up. The locals may be padded (and often are); We can only deduce a minimum amount of storage for these.

    The only way to know for sure is to actually analyze the assembler code a compiler generates, or look at the absolute difference of the stack pointer values at runtime - before and after a particular function was called.

    E.g.

    #include 
    
    void f()
    {
        register void* foo asm ("esp");
        std::cout << foo << '\n';
    }
    
    int main()
    {
        register void* foo asm ("esp");
        std::cout << foo << '\n';
        f();
    }
    

    Now compare the outputs. GCC on Coliru gives

    0x7fffbcefb410
    0x7fffbcefb400
    

    A difference of 16 bytes. (The stack grows downwards on x86.)

提交回复
热议问题