【问题标题】:printf printing garbage numberprintf 打印垃圾号
【发布时间】:2016-02-23 12:35:23
【问题描述】:

我挠头 8 个小时,只是为了在汇编中打印两个数字的总和。

这是我的简单代码:

.386
.model flat,stdcall
option casemap:none

.data
msg     dd  32h
str1 db "Hello",0
fmt    db "Sum: %X",0

.data?
retvalue dd ?

.code
include windows.inc
include user32.inc
includelib user32.lib
include kernel32.inc
includelib kernel32.lib
includelib MSVCRT
extrn printf:near
extrn exit:near

public main
main proc


         mov eax, 17h       ; 23
         mov ecx, 1Eh     ; 30
         add eax, ecx
         mov retvalue,eax
         ;push offset retvalue
         push offset msg
         ;push offset str1
         push offset fmt
         call printf 
         push 0
         call exit

main endp

end main

问题是最终的 printf 打印出垃圾数字:

这是输出:Sum: 403000

预期输出:Sum: 53

编辑:

当我尝试执行以下操作时,它不起作用

  push retvalue
  ;push  msg
  push str1
  push  offset fmt
  call printf 

我已经更改了我的fmt

fmt db "%d & %s",0

错误:

(32) : 错误 A2070: 无效指令操作数

编辑2:

在传递str1 的偏移量之后,程序仍然编译和链接,但似乎没有运行。

错误:

myapp.exe has stopped responding

代码:

fmt db "%d & %s",0

  push retvalue
  ;push  msg
  push offset str1
  push  offset fmt
  call printf 

【问题讨论】:

    标签: assembly x86 printf


    【解决方案1】:

    显示的代码打印msg 的地址,因为您执行push offset msgprintf 期望打印的值,而不是指向它的指针。因此,这应该有效:

         mov eax, 17h       ; 23
         mov ecx, 1Eh     ; 30
         add eax, ecx
         push eax
         push offset fmt
         call printf 
    

    【讨论】:

    • 当我尝试同时打印字符串和 Sum 时,它失败了。查看我的编辑
    • 有趣的是,字符串确实需要一个指针(因为它们是char*
    • 现在你弄错了参数顺序,格式字符串需要第二个字符串,但你把它作为第一个传递(因为你使用push,所以顺序颠倒了)