Search code examples
assemblyx86-16fasm

Why changing from 4 to 8 in cx prints one more word? In Assembly


Ignore the comments and the variables names in portuguese.

org 100h

escrita equ 40h
ecran equ 1

;executa o ciclo 3 vezes
mov [cont], 3
ciclo1:
mov ah, escrita
mov bx, ecran
mov cx, 4
mov dx, msg
int 21h
dec [cont]
jnz ciclo1

;escreve ‘---‘
mov ah, escrita
mov bx, ecran
mov cx, 4
mov dx, msg0
int 21h

;executa o ciclo 5 vezes
mov [cont], 5
ciclo2:
mov ah, escrita
mov bx, ecran
mov cx, 4
mov dx, msg
int 21h
dec [cont]
jnz ciclo2

;aguarda que se carregue numa tecla
mov ah, 07h
int 21h

;retorna ao sistema operativo
mov ah, 4ch 
int 21h

msg0 db '---',10
msg db "UBI", 10
cont rb 1

This code produces the following output:

enter image description here

I want to know why when I change

    mov ah, escrita
    mov bx, ecran
    mov cx, 4
    mov dx, msg0
    int 21h

mov cx, 4 to mov cx, 8 The program prints an extra layer of UBI, instead of 5 it prints 6 times UBI after the "---"

enter image description here


Solution

  • Your changed code

        mov ah, escrita
        mov bx, ecran
        mov cx, 8
        mov dx, msg0
        int 21h
    

    prints 4 bytes of msg0 and 4 bytes following it. Let's recall the definition:

    msg0 db '---',10
    msg db "UBI", 10
    

    The 4 bytes following msg0 is exactly msg. So, instead of ---\n you get ---\nUBI\n. Then you proceed to printing 5 lines of UBI.

    So you get an extra UBI line before the other UBIs, not after, which you might have suspected. You could check this fact by altering your msg before each output—e.g. by insertion of inc [msg] before int 21h in the msg printing loop and noticing that the first line isn't altered in the problematic case.