1

I am trying to understand assembly code. I am stuck in the portion where the pointer is assigned and the code after leaq command

This is my C code:

#include <stdio.h> #include<stdlib.h> int main(){ int x=50; int *y=&x; return 0; } 

This is my corresponding ASSEMBLY code:

.file "AssemlyCode.c" .def __main; .scl 2; .type 32; .endef .text .globl main .def main; .scl 2; .type 32; .endef .seh_proc main main: pushq %rbp .seh_pushreg %rbp movq %rsp, %rbp .seh_setframe %rbp, 0 subq $48, %rsp .seh_stackalloc 48 .seh_endprologue call __main movl $50, -12(%rbp) leaq -12(%rbp), %rax movq %rax, -8(%rbp) movl $0, %eax addq $48, %rsp popq %rbp ret .seh_endproc .ident "GCC: (GNU) 5.4.0" 
3
  • int y=&x; is invalid. y is not a pointer Commented Nov 30, 2016 at 6:21
  • Sorry i made a rookie mistake while writing the code..... I have corrected it now Commented Nov 30, 2016 at 6:29
  • Easier to read example: pass a pointer to a local to an external function. Then you can enable optimization without everything optimizing away. See source + asm on the Godbolt compiler explorer, which strips out all the .seh_ and other directives that set metadata for the object file. Commented Nov 30, 2016 at 7:39

1 Answer 1

6
 leaq -8(%rbp), %rax movl %eax, -4(%rbp) movl $0, %eax addq $48, %rsp popq %rbp ret 
  1. leaq saves address of variable x on the stack to register rax. Variable x is automatic variable on the stack, hence it address is calculated as offset from register that holds stack frame pointer(rbp).

  2. movl eax to stack saves argc argument to the stack.

  3. next step is to put return value in eax register from main function(return 0)

  4. two next opcodes are function epilogue - you are cleaning up used stack and restore previous frame pointer register.

  5. and the last one instruction is simple return.

Sign up to request clarification or add additional context in comments.

1 Comment

Would probably be good to point out why rbp-8 is &x: because it's on the stack. I'm not sure which part the OP doesn't understand, whether it's what LEA does, or why it's used that way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.