ARM 程序集:scanf 存储的值未正确保存。

ARM Assembly: Values stored by scanf are not saved correctly.

我正在尝试在 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"

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

ADD SP, SP, #4在第二次调用scanf之前,调用会覆盖之前输入的值。您可以在加载到 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}