Stack Overflow: Duplicate temporary allocation in stack space?

ε祈祈猫儿з 提交于 2019-12-04 01:18:11

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!