问题描述
最近,我在一次采访中遇到了这个问题:
我们如何确定特定函数在堆栈上消耗了多少存储空间?
Recently, I came across this question in an interview:
How can we determine how much storage on the stack a particular function is consuming?
推荐答案
它是完全由实现定义的——标准不会以任何方式对程序可能使用的底层机制强加要求.
It's completely implementation defined - the standard does not in any way impose requirements on the possible underlying mechanisms used by a program.
在 x86 机器上,一个堆栈帧由返回地址(4/8 字节)、参数和局部变量组成.
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.
例如
#include <iostream>
void f()
{
register void* foo asm ("esp");
std::cout << foo << '
';
}
int main()
{
register void* foo asm ("esp");
std::cout << foo << '
';
f();
}
现在比较输出.关于 Coliru 的 GCC 给出了
Now compare the outputs. GCC on Coliru gives
0x7fffbcefb410
0x7fffbcefb400
相差 16 个字节.(堆栈在 x86 上向下增长.)
A difference of 16 bytes. (The stack grows downwards on x86.)
这篇关于如何知道堆栈函数消耗了多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!