如何知道消耗了多少堆栈函数? [英] How to know how much stack function is consuming?

查看:82
本文介绍了如何知道消耗了多少堆栈函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我在一次采访中遇到了这个问题:
我们如何确定特定功能在堆栈上消耗了多少存储空间?

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 << '\n';
}

int main()
{
    register void* foo asm ("esp");
    std::cout << foo << '\n';
    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.)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆