How to make a loop with conditionals procedures in assembly

407 Views Asked by At

Im trying to make fizzbuzz in assembly x86 64 but i dont know how to make a loop that has conditional statements

I thought i would check for a condition and then jump to that procedure and then ret back. The problem is that if I return the label I will get a segfault for some reason.

The problem in the current code is that the fizzCondition will always execute

        mov ax, 6
        mov bl, 3
        div bl

        cmp ah, 0
        je fizzCondition

        ;check buzz condition etc..

        fizzCondition:
            mov eax, SYSWRITE
            mov edi, 1
            mov esi, fizz
            mov edx, 5
            syscall

        exit

if I do it like this I will get a segfault:

        mov ax, 6
        mov bl, 3
        div bl

        cmp ah, 0
        je fizzCondition

        exit

        fizzCondition:
            mov eax, SYSWRITE
            mov edi, 1
            mov esi, fizz
            mov edx, 5
            syscall

            ret
1

There are 1 best solutions below

2
fuz On

You need to use a call instruction to call a function. The call instruction records the return address on the stack so the function you called can return. If you just jump to the function, it'll return to whatever is on the stack, causing a crash. So to fix your code, change it to read:

    mov ax, 6
    mov bl, 3
    div bl

    cmp ah, 0
    jne around
    call fizzCondition           ; this executes only when AH==0
  around:

    exit

    fizzCondition:
        mov eax, SYSWRITE
        mov edi, 1
        mov esi, fizz
        mov edx, 5
        syscall

        ret

Another thing you'll have to pay attention to is that there is only one set of registers. fizzCondition overwrites the registers eax, edi, esi, and edx so you'll need to save their contents somewhere (e.g. on the stack) if you want them to be preserved.