How to know how much stack function is consuming?(如何知道堆栈函数消耗了多少?)
问题描述
最近,我在一次采访中遇到了这个问题:
我们如何确定特定函数在堆栈上消耗了多少存储空间?
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.)
这篇关于如何知道堆栈函数消耗了多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何知道堆栈函数消耗了多少?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
