如何知道堆栈函数消耗了多少?

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.)

这篇关于如何知道堆栈函数消耗了多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)