1

I'm kinda new with assembly, so i'm trying some different stuff just to varify that my knowledge is correct.

I tried to write this simple assembly code:

section .data
    string db "Your grade is %d", 0xa, 0

section .text
    global func
    extern printf

func:
    push 4
    push string
    call printf

    push dword [esp+8]
    add esp, 4
    jmp [esp-4]

which suppose to print Your grade is 4, but instead of adding 8 to esp and then use the ret command in the end, i tried something different. It does prints what i wanted, but then it falls (segFault).

Why? Can you explain that to me?

My thoughts: [esp+8] holds the return value, where we need to jump back at the end of the function. i pushed it (the return address) into the stack, raised the stack pointer back up and then jumped to [esp-4] which is where the return value i pushed two steps before is located.

ryden
  • 189
  • 6
  • 3
    I think you need to clean up the stack after printf with a add esp, 8 - otherwise the arguments will still be there – Dario Petrillo Feb 01 '22 at 14:05
  • 4
    You should generally avoid addressing under the stack pointer as you do not own that memory. If you insist on not using a `ret` you can do `mov ecx, [esp+8]; add esp, 12; jmp ecx`. You need to balance the stack in either case. – Jester Feb 01 '22 at 14:08
  • 1
    Related re: your messing around with `jmp`: [What is the x86 "ret" instruction equivalent to?](https://stackoverflow.com/a/54816685) (and other answers on that question that avoid tmp registers) – Peter Cordes Feb 01 '22 at 14:20

0 Answers0