堆栈溢出:在堆栈空间中重复临时分配? [英] Stack Overflow: Duplicate temporary allocation in stack space?

查看:146
本文介绍了堆栈溢出:在堆栈空间中重复临时分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct MemBlock {

    char mem[1024];

    MemBlock operator*(const MemBlock &b) const {

        return MemBlock();
    }

} global;

void foo(int step = 0) {

    if (step == 10000)
    {
        global = global * MemBlock();
    }
    else foo(step + 1);
}

int main() {

    foo();
    return 0;
}




程序接收信号SIGSEGV,分段故障。
0x08048510 in foo(step = 4000)at t.cpp:12
12 void foo(int step = 0){

Program received signal SIGSEGV, Segmentation fault. 0x08048510 in foo (step=4000) at t.cpp:12 12 void foo(int step = 0) {

看来,MemBlock()实例花费了很多堆栈内存,虽然它还没有被调用(check gdb info)。

It seems that the MemBlock() instance costs a lot of stack memory though it hasn't been called yet (check gdb info).

我使用 global = global * global 代替,程序正常退出。

And when I use global = global * global instead, the program exits normally.

任何人都可以解释内部机制? / p>

Can anybody explain the inner mechanism?

推荐答案

编译器保留每个实例上的 MemBlock 无论 foo 中的控制流如何,都调用 foo 。这是一个常见的优化,以防止必须重复调整函数内的堆栈指针。相反,编译器计算所需的最大堆栈空间,并且在输入函数时,按照该数量调整堆栈指针。

The compiler is reserving the stack space for the MemBlock instance on each call to foo, regardless of the control flow within foo. This is a common optimisation to prevent having to repeatedly adjust the stack pointer within the function. Instead, the compiler calculates the maximum stack space required and on entry to the function adjusts the stack pointer by that amount.

观察到,这导致为实际上没有使用的对象保留的堆栈空间。答案是不这样做;如果你只是在某些分支中使用一些大足迹的对象,然后将这些分支分成自己的函数。

As you've observed, this results in losing stack space reserved for objects you don't actually use. The answer is to not do that; if you're only using some large-footprint objects within certain branches then separate those branches out into their own function.

顺便说一下,这就是为什么古老版本的C需要所有函数范围变量要在函数的顶部声明;所以编译器可以很容易地计算出函数需要多少堆栈空间。

Incidentally, this is why archaic versions of C required all function-scope variables to be declared at the top of the function; so that the compiler can easily work out how much stack space the function requires.

这篇关于堆栈溢出:在堆栈空间中重复临时分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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