首页 > 解决方案 > 装配循环循环太多次

问题描述

我对组装很陌生(昨天开始学习)并且有循环问题:

下面的代码应该打印值 0-49,但它会打印 0-49,然后是大约 20 行垃圾(我假设这是其他程序/程序的其他位正在使用的堆栈的一部分)。我预计问题是第二个循环,.loop因为它打印错误的行数,并且打印由.loop.

我正在使用 FASM (Flat Assembler) 程序来编译它。

代码:

format PE console
include "win32ax.inc"
start:
    mov ecx, 50 ;number of loops
    .mainloop: ;for testing purposes, just pushes 49-0 onto the stack
        push ecx ;push onto stack
        dec ecx ;decrement counter
        jnz .mainloop ;jump if counter not zero

    mov ecx, 50 ;reset ecx (counter)
    .loop: ;prints the stack, should print 0-49 but also prints garbage at the end
        pop eax ;pop from stack to eax
        cinvoke printf,formatstring,eax ;print eax
        dec ecx ;decrement counter
        jnz .loop ;loop if counter not zero
    int 15;wait 5 seconds ish
    invoke ExitProcess ;exit

formatstring    db "%d",13,10,0 ;to print digits instead of ASCII chars

section '.idata' import data readable ;stuff I copied but seems to work
    library msvcrt,'msvcrt.dll',\ ;don't understand it
        kernel32,'kernel32.dll'   ;^
    import  msvcrt,printf,'printf';^^
    import  kernel32,ExitProcess,"ExitProcess";^^^

提前致谢。

ps 如何使用语法高亮格式化代码?

标签: windowsassemblyx86fasm

解决方案


正如zx485所指出的那样,问题在于cinvoke printf,formatstring,eax更改了寄存器。ECX事实证明它也改变了EDX寄存器。

为了解决这个问题,我改为使用EBX寄存器,它没有cinvoke printf,formatstring,eax.

我希望这可以帮助别人。

编辑:melpomene 发布了一个更好的答案。


推荐阅读