汇编程序奇怪的行为

时间:2014-04-01 06:08:44

标签: assembly x86 ascii stdout masm32

我试图在MASM中编写一个小程序,它将接受一串用户输入,从每个字符的ASCII值中减去4,然后输出新字符。

这大部分都是成功的,除非调用StdOut时,它不仅打印当前修改的字符,还打印下一个字符。

我一直试图找出几个小时内发生的事情但仍然没有线索。这是我的代码:

.486
.model flat, stdcall
option casemap :none

include \masm32\include\windows.inc
include \masm32\macros\macros.asm

include \masm32\include\masm32.inc
include \masm32\include\gdi32.inc
include \masm32\include\user32.inc
include \masm32\include\kernel32.inc

includelib \masm32\lib\masm32.lib
includelib \masm32\lib\gdi32.lib
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib

.data?
    inputtxt dw 10000 dup(?)
    current  dd           ?

.code
start:
    call main
    exit

main proc
    Invoke StdIn, addr inputtxt, 10000
    xor esi, esi

    processLoop:
        movzx eax, inputtxt[esi]        ; Get the character at index ESI
        sub eax, 4                      ; Subtract 4 from the character's ASCII code
        mov current, eax                ; StdOut can't print a register
        Invoke StdOut, addr current     ; Print the character: the problem lies here.
        inc esi                         ; Increment the loop counter
        cmp byte ptr[inputtxt[esi]], 0  ; If the next character is NUL, we're done
        jne processLoop                 ; If it's not, loop again
        ret

main endp

end start

以下是输入和输出示例:

输入:HE

输出:DEA

DA是正确的,但E不正确,并在与D相同的传递中打印。

目前没有结束的人是否会尝试弄清楚这里发生了什么?

1 个答案:

答案 0 :(得分:1)

汇编程序假定您的movzx应该将16位数据转换为32位,因为您没有为指令中的源数据指定大小。

添加byte ptr说明符:

; Move a byte from [inputtxt+esi] to eax, zero-extended
movzx eax, byte ptr inputtxt[esi]