Reputation: 758
I have written following x86 assembly code for NASM assembler.
hello.asm
[org 0x7c00]
mov bx, HELLO_MSG
call print_string
mov bx, GOODBYE_MSG
call print_string
jmp $
%include "print_string.asm"
HELLO_MSG:
db 'hello, world',0
GOODBYE_MSG:
db 'good bye',0
times 510-($-$$) db 0
dw 0xaa55
print_string.asm
print_string:
mov ah, 0x0e
push bx
loop:
cmp WORD [bx], 0
je end
mov al, [bx]
int 0x10
inc bx
jmp loop
end:
pop bx
ret
I have run the code in bochs 2.2.6 emulator.
Expected outpur
hello worldgood bye
output i am getting
hello world good byegood bye
Why good bye
is printed twice? also notice there is an extra space after hello, world
. Where it is coming from?
NB: If I print only one string code works just fine.
Upvotes: 1
Views: 771
Reputation: 7483
Your problem is coming from the line
cmp WORD [bx], 0
This is saying "compare the word at the address pointed to by bx with 0." However, the string that you are looking at is made of bytes, not words. In order for this compare to succeed, it would have to find 2 bytes in a row (aka a word) that both contain zeros.
This doesn't happen at the end of HELLO_MSG, so it just keeps printing characters, walking right thru the following string (GOODBYE_MSG), until it finally finds a pair at times 510-($-$$) db 0
.
This also explains the extra space you are seeing, since you are actually printing the 0 at the end of HELLO_MSG.
Upvotes: 3