At what moment is memory typically allocated for local variables in C++?

后端 未结 5 843
故里飘歌
故里飘歌 2021-01-01 11:04

I\'m debugging a rather weird stack overflow supposedly caused by allocating too large variables on stack and I\'d like to clarify the following.

Suppose I have the

5条回答
  •  耶瑟儿~
    2021-01-01 11:19

    On many platforms/ABIs, the entire stackframe (including memory for every local variable) is allocated when you enter the function. On others, it's common to push/pop memory bit by bit, as it is needed.

    Of course, in cases where the entire stackframe is allocated in one go, different compilers might still decide on different stack frame sizes. In your case, some compilers would miss an optimization opportunity, and allocate unique memory for every local variable, even the ones that are in different branches of the code (both the 1 * 1024 array and the 512 * 1024 one in your case), where a better optimizing compiler should only allocate the maximum memory required of any path through the function (the else path in your case, so allocating a 512kb block should be enough). If you want to know what your platform does, look at the disassembly.

    But it wouldn't surprise me to see the entire chunk of memory allocated immediately.

提交回复
热议问题