【问题标题】:Need help in this following NASM task在以下 NASM 任务中需要帮助
【发布时间】:2013-02-14 11:53:15
【问题描述】:

我在 Ubuntu11.04 的 NASM 中编写了一个程序,它将接受 2 个输入数字并产生一个总和。程序如下:

    section .data
       msg1:    db "the numbers are:%d%d",0
       msg3:    db "REsult= %d",10,0
    section .bss
       a resd 1
       b resd 1
       sum resd 1
    section .text
      global main
      extern printf,scanf
    main:
;; push ebp
;; mov ebp,esp
;; sub esp,10

      push a
      push b
      push msg1
      call scanf
      add esp,12

      mov eax,DWORD[a]
      add eax,DWORD[b]
      mov DWORD[sum],eax

      push DWORD[sum]
      push msg3
      call printf
      add esp,8

;; mov esp,ebp
;; pop ebp
       ret

你能帮我找出我在这里犯的错误吗?如果您向我提供 NASM 中的任何教程,无论是视频还是文本,我也将不胜感激。我已经获得了汇编语言艺术或 NASM 手册。但是第一个不是基于 NASM 的,第二个对于像我这样的初学者来说很难获得。

感谢

【问题讨论】:

  • 错误是什么?有什么症状?
  • @EarlGray:我做了调试。它表明输入没有存储在eax中。所以结果每次都显示为0。最令人震惊的是在输入时没有显示“数字是”消息。
  • msg1 需要以零结尾。您还需要干净地退出。取消注释ret,或致电exit
  • @FrankKotler:我不确定你是否按照你所说的修改执行了这个程序。这没用。为了您的方便,我重新编辑了上面的代码
  • 你说得对,我没试过。你是对的,它不起作用。显然,scanf 不会打印提示(我对 C 不是很熟悉 - 我可以向您展示如何通过系统调用来做到这一点)。我通过先打印提示(使用printf)解决了这个问题,然后只使用"%d%d", 0 调用scanf。我应该避免尝试回答涉及 C 的问题!

标签: c linux assembly x86 nasm


【解决方案1】:

这应该可以帮助您:

global main
extern printf, scanf, exit

section .data 
scanf_fmt       db  "%d %d", 0
printf1_fmt     db  "The numbers entered are: %d and %d,", " The result = %d", 10, 0

main:
    push    ebp
    mov     ebp, esp
    sub     esp, 8                          ; make room for 2 dwords

    lea     eax, [ebp - 4]                  ; get pointers to our locals
    lea     ecx, [ebp - 8]                  ;
    push    eax                             ; give pointers to scanf
    push    ecx                             ;
    push    scanf_fmt                       ;
    call    scanf                           ; read in 2 dwords
    add     esp, 12

    mov     eax, dword [ebp - 4]            ; add em together
    add     eax, dword [ebp - 8]            ;

    push    eax                             ; total
    push    dword [ebp - 4]                 ; second num
    push    dword [ebp - 8]                 ; first num
    push    printf1_fmt                     ; format string
    call    printf                          ; show it
    add     esp, 16                         

    add     esp, 8                          ; restore stack pointers
    mov     esp, ebp
    pop     ebp
    call    exit                            ; linking agaist the c libs, must use exit.

输出:

【讨论】:

    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    相关资源
    最近更新 更多