为什么GCC为C数组分配太多堆栈空间

考虑以下程序:

int main()
{
   int arr[8];
}

在 linux 20 上使用 gcc 9.3.0 编译时,文件的反汇编一开始看起来像这样(这不是上面代码的整个汇编!):

? 72: int dbg.main (int argc, char **argv, char **envp);
?           ; var int[8] arr @ rbp-0x30
?           ; var int64_t canary @ rbp-0x8
?           0x00001169      f30f1efa       endbr64                     ; test.c:2 { ; int main();
?           0x0000116d      55             push rbp
?           0x0000116e      4889e5         mov rbp, rsp
?           0x00001171      4883ec30       sub rsp, 0x30

arr只有 8 个整数 = 8 * 4 个字节长 ( sub rsp, 0x30)时,为什么汇编程序在堆栈上分配 0x30 = 48 个字节?

回答

那是:

  • 数组的 32 个字节

  • 堆栈金丝雀的8 个字节

  • 另外 8 个字节以确保16 字节堆栈对齐。

总计:48 个字节。

  • But mostly because it's not optimized. Since it is a leaf function it does not need to align the stack, nor does it need any allocation as long as locals fit into the red zone. Also the `format` mentioned in the comment seems to indicate this is assembly for a different program than shown.
  • @Jester: For that matter, `arr` could be optimized out altogether; with optimization you just get `xor eax, eax ; ret`. I found the `format` mysterious because it appears to overlap `arr`.

以上是为什么GCC为C数组分配太多堆栈空间的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>