What happens to the value stored in [rbp-1] after pop rbp

325 Views Asked by At

I am total newbie to assembly, I learning assembly by compiling c code to assembly.

For this c++ code


int foo() {
    bool x = true;
    return 1;
} 

This is the generated assembly code (intel syntax)

foo():
        push    rbp
        mov     rbp, rsp
        mov     BYTE PTR [rbp-1], 1
        mov     eax, 1
        pop     rbp
        ret

You can check compiler explorer link here

In this instruction

        mov     BYTE PTR [rbp-1], 1

we are storing 1 in stack and its address is [rbp - 1]

  mov    eax, 1
  pop    rbp
  ret

Here we are setting the return value to be 1 and popping stack and storing its value in rbp.

My doubt is how we are storing 1 in address in [rbp - 1] since rsp should always point at top (in this case down) of stack, after this instruction mov BYTE PTR [rbp-1], 1 the top should be [rbp-1] but rsp still be pointing to rbp.

Isnt the correct code should be something like this

   sub rsp, 1
   mov BYTE PTR [rbp - 1], 1

In this way the rsp will always point to the top.

My second doubt is what happens to the value stored in [rbp-1] after ret. Is it somehow gets automatically cleaned up.

0

There are 0 best solutions below