Search code examples
loopsassemblysegmentation-faultnasmcmp

NASM (assembly) segmentation fault on 2nd loop iteration


I keep getting a segmentation fault the second time I go through the loop and enter E (intended to exit the loop). If I enter E the first time, it exits just fine. Hopefully I'm just being dumb here and someone can suggest an easy fix!

Thanks for your time.

Declarations:

segment .bss
        a resd 1
        b resd 1
        op resb 2

Main:

loop:

    call read_int    ;read two integers, then a char
    mov [a], eax
    call read_int
    mov [b], eax
    call read_char
    call read_char   ;takes newline input

    cmp al, 'E'      ;if char is E, then exit
    je exit

    call loop        ;start over

exit:
    dump_regs 0      ;completes, but then seg faults if the loop has run more than once

Solution

  • I see a couple of problems/potential problems right off the bad:

    1) when you "call" a subroutine, you generally need to a) update the stack (in your subroutine) and b) clear the stack (after you return).

    You haven't shown us "read_int" or "read_char", but I suspect that's probably the case.

    2) BAD: call loop. BETTER: jmp loop.

    You can find some good NASM examples here: http://www.csee.umbc.edu/portal/help/nasm/sample.shtml