I am trying to understand how assembly is generated for c. I wrote a sample program and disassembled it for the same.
int main()
{
int a = 100;
}
Assembly generated:
pushq %rbp #
movq %rsp, %rbp #,
subq $48, %rsp #,
call __main #
movl $100, -4(%rbp) #, a
leave
ret
That is pretty straight forward for me. But i dont understand the assembly when i include a pointer in it.
C Program:
int main()
{
int a = 100;
int *p = &a;
}
Assembly generated:
pushq %rbp #
movq %rsp, %rbp #,
subq $48, %rsp #,
call __main #
movl $100, -12(%rbp) #, a
leaq -12(%rbp), %rax #, tmp59
movq %rax, -8(%rbp) # tmp59, p
leave
ret
I dont understand why the local variable a is now pushed to a different offset with in the stack compared to tha earlier snip which doesnt have a pointer in it.
Question #2: If i have 4 local variables my stack frame is subq $48, %rsp, but if i convert one of the local variable to pointer it is subq $64. why is it so.
C code:
int main()
{
int a = 100;
int *p = &a;
int b = 10;
int c = 20;
}
Assembly:
pushq %rbp #
movq %rsp, %rbp #,
subq $64, %rsp #,
call __main #
movl $100, -20(%rbp) #, a
leaq -20(%rbp), %rax #, tmp59
movq %rax, -8(%rbp) # tmp59, p
movl $10, -12(%rbp) #, b
movl $20, -16(%rbp) #, c
leave
ret
Also it would be helpful, if you guys can explain why the stack frame is 2 * 16 bytes aligned (32 bytes) for a main function with no local variables. Guess it should be for some book keeping exercise, but whats the exact reason?
Thanks,