How does the gcc determine stack size the function based on C will use?

后端 未结 2 1876
-上瘾入骨i
-上瘾入骨i 2020-12-18 06:23

I write program in C programming language, and I use objdump to translate the executable file to asm file. I have no idea how gcc determine the stack size the function will

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 06:42

    How does the gcc determine stack size the function based on C will use?

    It does so by looking at the size of the variables used and adding them. (As a first approximation, anyway. For performance and correctness reasons, alignment and padding and whatever else might be added to the allocated amount as well.)

    Will the gcc allocate really 1024 * 1024 bytes space for function a?

    If you tell it to do so (you disable optimizations), it most probably will. (Not 1024 * 1024 bytes, though -- rather 1024 * 1024 * sizeof(int) bytes. At least.) But you can just go ahead and compile it and look at the generated assembly.

    But your function is quite a simple one, and its behavior is trivial to reason about, so I'd expect any decent compiler to optimize away the array declaration. (But again, look at what actual assembly it outputs. It might vary from version to version, with flags, with platforms, etc.)

    If the function is a little complicate, sometimes a lot of local variables, how does the compiler determine the stack size?

    The complexity of your function does not matter. If it's too complicated, then maybe the compiler can do less optimizations. But it definitely can compute the upper bound of the necessary memory by - naively - adding all the sizes of the variables used.

提交回复
热议问题