2

Working with assembly code and wondering why I get a seg fault with the instruction subl $8, %esp?

        pushl %ebp
    movl %esp, %ebp

        movl 16(%ebp), %esi
        movl 12(%ebp), %edi
        movl 8(%ebp), %eax
        movl $0, %ebx
        subl $8, %esp
        jmp .LL1

.LL1:
        cmpl %ebx, %esi
        je .LL2
        movl %ebx, 4(%esp)
        movl %eax, (%esp)
        addl $1, %ebx
        jmp .LL1

.LL2:
    popl %ebp
    ret

segfault on subl $8, %esp

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
AYCHSTACKS
  • 31
  • 2
  • Also [Does it matter where the ret instruction is called in a procedure in x86 assembly](https://stackoverflow.com/q/46714626) for a version not using an EBP/RBP frame pointer. – Peter Cordes Dec 18 '21 at 02:11

1 Answers1

5

Are you sure that the code segfaults on subl $8, %esp?

In your code, you subtract 8 from the stack pointer, but never restore the value. The address to return to is no longer the most recent thing on the stack when you execute ret.

The instruction

movl %esp, %ebp

copies the original value of %esp to %ebp. When you return, you restore the original of %ebp with popl, but never restore %esp, so you return to some garbage address.

Before the line

popl %ebp

add

movl %ebp, %esp

to correct the stack pointer before returning.

Thomas Jager
  • 4,836
  • 2
  • 16
  • 30
  • wonderful suggestion, I updated the stack pointer in LL2 thank you kindly – AYCHSTACKS Jul 26 '19 at 17:35
  • 1
    @AYCHSTACKS If an answer solved your problem, you're able to mark is as the accepted answer for your question. I don't mean to pressure you to accept mine, just making sure that you know that you can do that. – Thomas Jager Jul 26 '19 at 18:38
  • 2
    @AYCHSTACKS Specifically if you don't know how to accept as an answer or would like info on how to accept an answer (and why) you can find useful information here: https://meta.stackexchange.com/a/5235/271768 – Michael Petch Jul 26 '19 at 18:45