Why gcc disassembler allocating extra space for local variable?

前端 未结 3 488
萌比男神i
萌比男神i 2020-12-11 16:49

I have written simple function in C,

void GetInput()
{
    char buffer[8];
    gets(buffer);
    puts(buffer);
}

When I disassemble it in g

相关标签:
3条回答
  • 2020-12-11 17:29

    Besides the other answers already given, gcc will prefer to keep the stack 16-byte aligned for storing SSE values on the stack since some (all?) of the SSE instructions require their memory argument to be 16-byte aligned.

    0 讨论(0)
  • 2020-12-11 17:29

    This more builds upon Pascal's answer, but in this case, it's probably because of the stack protection mechanism.

    You allocate 8 bytes, which is fair enough and taken into account with the stack pointer. In addition, the current stack protection address is saved to %ebp, which points to the top of the current stack frame on the following lines

    0x0804846a <+6>: mov    %gs:0x14,%eax
    0x08048470 <+12>:    mov    %eax,-0x4(%ebp)
    

    This appears to take a four bytes. Given this, the other four bytes are probably for alignment of some form, or are taken up with some other stack information on the following lines:

    => 0x08048475 <+17>:    lea    -0xc(%ebp),%eax
       0x08048478 <+20>:    mov    %eax,(%esp)
    
    0 讨论(0)
  • 2020-12-11 17:34

    Two things:

    1. The compiler may reserve space for intermediate expressions to which you did not give names in the source code (or conversely not allocate space for local variables that can live entirely in registers). The list of stack slots in the binary does not have to match the list of local variables in the source code.
    2. On some platforms, the compiler has to keep the stack pointer aligned. For the particular example in your question, it is likely that the compiler is striving to keep the stack pointer aligned to a boundary of 16 bytes.

    Regarding your other question that you should have asked separately, xor %gs:0x14,%eax is clearly part of a stack protection mechanism, enabled by default. If you are using GCC, turn it off with -fno-stack-protector.

    0 讨论(0)
提交回复
热议问题