Botond Balázs
Botond Balázs

Reputation: 2500

How to write a procedure to print a string and a newline character in x86 assembly?

I'm trying to write a some reusable procedures to print strings in x86 assembly:

print_str works fine, but for some reason, print_nl and print_strnl both go into an infinite loop.

Here's my code an the output:

;
; String handling
;

code segment para public 'CODE'
assume cs:code ds:data ss:stack es:nothing

main proc far
    push    ds
    xor     ax, ax
    push    ax
    mov     ax, data
    mov     ds, ax

    mov     si, offset t_something
    cld
    call    print_nl

    ret
main endp

;
; Print a 0-terminated string
;
; Parameters:
; - SI: the offset of the string
;
print_str proc
print_str_start:
    lodsb
    cmp     al, 0
    je      print_str_end
    mov     ah, 14
    int     10h
    jmp     print_str_start

print_str_end:
    ret
print_str endp

;
; Print a newline character
;
print_nl proc
    mov     si, offset t_newline
    cld
    call    print_str
print_nl endp

;
; Print a 0-terminated string, then a newline character
;
; Parameters:
; - SI: the offset of the string
;
print_strnl proc
    call    print_str
    call    print_nl
print_strnl endp

data segment para public 'DATA'

t_newline     db  13, 10, 0
t_something   db  'SOMETHING', 0

data ends

stack segment para stack
    dw  100 DUP (?)
stack ends

end main

Output:

SOMETHING
SOMETHING
SOMETHING
SOMETHING
SOMETHING
SOMETHING
SOMETHING
(...) - infinite loop

Could you please explain what the problem is?

Upvotes: 0

Views: 1440

Answers (1)

Jester
Jester

Reputation: 58762

Make sure the endp actually adds a ret for you. Add it yourself if it doesn't. Alternatively, you can just use jmp for the final call instructions, such as:

;
; Print a newline character
;
print_nl proc
    mov     si, offset t_newline
    cld
    jmp     print_str
print_nl endp

;
; Print a 0-terminated string, then a newline character
;
; Parameters:
; - SI: the offset of the string
;
print_strnl proc
    call    print_str
    jmp     print_nl
print_strnl endp

Upvotes: 1

Related Questions