Qwerp-Derp
Qwerp-Derp

Reputation: 487

Assembly - jmp and cmp result in infinite loop

Here is my code:

%include "io.inc"

section .data
var DB 0
var2 DB 0

section .text
global CMAIN

print:
    PRINT_DEC 1, var
    inc BYTE [var]
    mov eax, [var]
    ret

forLoop:
    call print
    cmp eax, [var2]
    jle forLoop
    ret

CMAIN:
    GET_DEC 1, var2
    call forLoop
    ret

This uses Simple-ASM's default library.

When given with the input 5 (which is then placed into var2), I expect an output of:

012345

However, when given the input 5, I get this instead:

01234567891011...127128-127-126...-10123...

It appears that the cmp and jle don't work properly when checking the two numbers, and forLoop never stops calling itself, which results in var being continuously inced.

When I placed a PRINT_DEC 1, var2 after the GET_DEC statement, like so:

CMAIN:
    GET_DEC 1, var2
    PRINT_DEC 1, var2
    call forLoop
    ret

And comment out the other PRINT_DEC line, there's no output at all.

How can I fix this?

Upvotes: 1

Views: 845

Answers (1)

melpomene
melpomene

Reputation: 85767

    mov eax, [var]

eax is a 32-bit register, so this instruction copies 4 bytes from the label var into eax. Similarly,

    cmp eax, [var2]

compares eax with the 4 bytes at var2. This is a problem because var and var2 only store 1 byte each.

Fix:

    mov al, [var]

and

    cmp al, [var2]

respectively. al is an 8-bit register (it's the lowest byte of eax), so this way we properly copy/compare 1-byte quantities.

Upvotes: 1

Related Questions