assemblyx86-64nasm

Why does my Assembly program continue to execute after reaching the value 10, even with the correct comparison?


I am writing a program in Assembly x86-64 where the goal is to increment a value (num) until it reaches 10. However, despite using the correct comparison to check if num is less than 10, the program continues executing and printing values after 10:

[BITS 64]
default rel

section .data
extern ExitProcess, printf
    msg db "%d", 10, 0
    num dq 0

section .text
    global main

main:
    sub rsp, 56
again:
    mov r8, [num]
    add r8, 1
    mov [num], r8

    lea rcx, [msg]
    mov rdx, [num]
    call printf

    cmp r8, 10
    jge end

    jmp again

end:

    xor rax, rax
    call ExitProcess

Doing this prints:

1
2
3
4
5
6
7
8
9
10 ; <--- ??? don´t stop
11
12
13
14
15
16
17
18
19
20
21
[...]

But it should stop when it reaches 10. Why is this happening?


Solution

  • The register r8 is overwritten ("clobbered") inside the function printf. You need to reload it from memory before your cmp instruction. Alternatively you could rearrange your code so the cmp is done together with the code to do the increment.