Strange output with Irvine's WriteString

Dalton Conley picture Dalton Conley · Sep 27, 2010 · Viewed 7.7k times · Source

the point of the following program is to print out the letter "c" with the combination of every background and foreground color.

In the library I'm using the colors are defined 0-15 and with the following code:

mov eax,FOREGROUND + (BACKGROUND * 16) 
call SetTextColor 

Here is my code:

INCLUDE Irvine32.inc
.data

character BYTE "c"
count DWORD ?
background DWORD 0

.code
main PROC
    call Clrscr

    mov ecx, 15                             ; our main counter 0-15 colors

L1:     
    mov count, ecx                          ; store our outer loop counter
    mov ecx, 15                             ; set out inner loop counter
L2:     
    ; since our color is defined like so... mov eax,FOREGROUND + (BACKGROUND * 16)
    mov eax, count                          ; setup our foreground color
    add eax, background                     ; setup our background color
    call SetTextColor

    ;  instead of multiplying each background color by 16, we are going to 
    ; add 16 each time. 
    add background, 16                      

    ; print the character
    mov edx, OFFSET character
    call WriteString 
    loop L2

    mov ecx, count                          ; reset our outside loop
    loop L1

    call Crlf
    exit
main ENDP

END main

Now, I'm using windows 7, the above code "works" but for some reason, it goes to a certain point, the program stops, and the computer starts beeping. Also, at a certain point in the program, it starts printing random characters with the letter c.. here is my output:

c♀c♀c♀c♀c♀c♀c♀c♀c♀c♀c♀c♀c♀c♀c♀c♂c♂c♂c♂c♂c♂c♂c♂c♂c♂c♂c♂c♂c♂c♂c
c
c
c
c
c
c
c
c
c
c
c
c
c
c
c       c       c       c       c       c       c       c       c       c
c       c       c       c       c       cccccccccccccccc♠c♠c♠c♠c♠c♠c♠c♠c♠c♠c♠c♠c
♠c♠c♠c♣c♣c♣c♣c♣c♣c♣c♣c♣c♣c♣c♣c♣c♣c♣c♦c♦c♦c♦c♦c♦c♦c♦c♦c♦c♦c♦c♦c♦c♦c♥c♥c♥c♥c♥c♥c♥c
♥c♥c♥c♥c♥c♥c♥c♥c☻c☻c☻c☻c☻c☻c☻c☻c☻c☻c☻c☻c☻c☻c☻c☺c☺c☺c☺c☺c☺c☺c☺c☺c☺c☺c☺c☺c☺c☺
Press any key to continue . . .

Can anyone tell me why this is happening?

Answer

rkhb picture rkhb · Dec 15, 2015

Irvine's WriteString needs a "null-terminated string". Some can download the help as CHM-file here (IrvineLibHelp.exe).

It's a little bit sloppy to say "EDX = points to string". EDX just points to an memory address identifiable by a label (here: "character"). WriteString will get byte for byte from that location and write it as character or control directive regardless of his real type or intention until it comes across a byte with the value 0. MASM has no directive to define a string with the last 0, so it has to be added manually:

character BYTE "c", 0

An alternative way to print a character is to use WriteChar:

...
; print the character
mov al, character
call WriteChar
loop L2

mov ecx, count                          ; reset our outside loop
loop L1
...