How to know how much stack function is consuming?

后端 未结 4 1665
天涯浪人
天涯浪人 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:41

    As stated by other answers, the program stack is a concept which is not specified within the language itself. However with a knowledge how typical implementation works, you can assume that the address of the first argument of a function is the beginning of its stack frame. The address of the first argument of a next called function is the beginning of the next stack frame. So, they probably wanted to see a code like:

    void bar(void *b) {
       printf("Foo stack frame is around %lld bytes\n", llabs((long long)b - (long long)&b));
    }
    
    void foo(int x) {
      bar(&x);
    }
    

提交回复
热议问题