【问题标题】:ARM Assembly: Values stored by scanf are not saved correctly.ARM 汇编:scanf 存储的值未正确保存。
【发布时间】:2016-07-06 16:15:32
【问题描述】:

我正在尝试在 ARM 程序集中使用 scanf 读取多个值(一次一个)。我设法让 scanf 部分工作,它显然保存了正确的值。但是当我想检索它们时,我只会得到最后一个数字,而其他数字会得到别的东西。

这就是它给我的:

Enter a number: 1  
Enter a number: 2  
You entered: 2129322344 and 2.  

应该是You entered 1 and 2.

我的代码如下所示:

  .global main
  .func main

main:
  PUSH {LR}
  LDR R0, =entryMessage
  BL printf
  SUB SP, SP, #8
  LDR R0, =scanformat
  MOV R1, SP
  BL scanf        @ Number is saved in SP - 8
  LDR R0, =entryMessage
  BL printf
  ADD SP, SP, #4
  LDR R0, =scanformat
  MOV R1, SP
  BL scanf        @ Number is saved in SP - 4
  ADD SP, SP, #4  @ Restore SP to original
  SUB SP, SP, #8  @ Prepare to read SP - 8 for first number
  LDR R1, [SP]    @ Read first number
  ADD SP, SP, #4  @ Prepare to read SP - 4 for second number
  LDR R2, [SP]    @ Read second number
  ADD SP, SP, #4  @ Restore SP to original
  LDR R0, =printMessage
  BL printf
  POP {PC}

_exit:
  BX LR

.data
  entryMessage: .asciz "Enter a number: "
  scanformat: .asciz "%d"
  printMessage: .asciz "You entered: %d and %d.\n"

谁能告诉我为什么只有最后一个值被正确读取?

【问题讨论】:

    标签: assembly arm scanf libc


    【解决方案1】:

    您在第二次调用scanf 之前ADD SP, SP, #4,然后调用会覆盖之前输入的值。在加载到R1R2 之前,您可以按相反的顺序存储它们。所以堆栈指针永远不会高于您要使用的存储值。

    main:
        PUSH {LR}
        LDR R0, =entryMessage
        BL printf
    
        SUB SP, SP, #4  @ Reserve space for the first number entry
        LDR R0, =scanformat
        MOV R1, SP
        BL scanf        @ Number is saved at original SP - 4
    
        LDR R0, =entryMessage
        BL printf
    
        SUB SP, SP, #4  @ Reserve space for the second number entry
        LDR R0, =scanformat
        MOV R1, SP
        BL scanf        @ Number is saved at original SP - 8
    
        LDR R2, [SP]    @ Read second number
        ADD SP, SP, #4  @ Prepare to read first number
        LDR R1, [SP]    @ Read first number
        ADD SP, SP, #4  @ Restore SP to original
        LDR R0, =printMessage
        BL printf
    
        POP {PC}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      相关资源
      最近更新 更多