简体   繁体   中英

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 inc ed.

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?

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM