小编Hen*_*lle的帖子

为什么编译器在堆栈中分配的不仅仅是需要的?

我有一个简单的C程序.比方说,我有一个长度为20的int和一个char数组.我总共需要24个字节.

int main()
{
   char buffer[20];
   int x = 0;
   buffer[0] = 'a';
   buffer[19] = 'a';
}
Run Code Online (Sandbox Code Playgroud)

堆栈需要与16字节边界对齐,因此我假设编译器将保留32个字节.但是当我使用gcc x86-64编译这样的程序并读取输出程序集时,编译器会保留64个字节.

..\gcc -S -o main.s main.c
Run Code Online (Sandbox Code Playgroud)

给我:

    .file   "main.c"
    .def    __main; .scl    2;  .type   32; .endef
    .text
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    pushq   %rbp                        # RBP is pushed, so no need to reserve more for it
    .seh_pushreg    %rbp
    movq    %rsp, %rbp
    .seh_setframe   %rbp, 0
    subq    $64, %rsp                   # Reserving the 64 bytes
    .seh_stackalloc 64
    .seh_endprologue …
Run Code Online (Sandbox Code Playgroud)

c memory compiler-construction stack allocation

4
推荐指数
1
解决办法
1013
查看次数

标签 统计

allocation ×1

c ×1

compiler-construction ×1

memory ×1

stack ×1