Assembly 臂部件:scanf存储的值未正确保存。
我试图在ARM组件中使用scanf读取多个值(一次一个)。我设法让scanf部分工作,它显然保存了正确的值。但是当我想找回它们时,我只得到了最后一个正确的数字,而其他的则得到了其他的东西 这就是它给我的:Assembly 臂部件:scanf存储的值未正确保存。,assembly,arm,scanf,libc,Assembly,Arm,Scanf,Libc,我试图在ARM组件中使用scanf读取多个值(一次一个)。我设法让scanf部分工作,它显然保存了正确的值。但是当我想找回它们时,我只得到了最后一个正确的数字,而其他的则得到了其他的东西 这就是它给我的: Enter a number: 1 Enter a number: 2 You entered: 2129322344 and 2. 应该是您输入了1和2。 我的代码如下所示: .global main .func main main: PUSH {LR} LD
Enter a number: 1
Enter a number: 2
You entered: 2129322344 and 2.
应该是您输入了1和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"
有人能告诉我为什么只有最后一个值被正确读取 在第二次调用scanf
之前,您ADD SP,SP,#4
,然后调用将覆盖先前输入的值。在加载到R1
和R2
之前,可以按相反顺序存储它们。因此,堆栈指针永远不会高于要使用的存储值
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}
在第二次调用scanf
之前,您添加SP,SP,#4,然后调用将覆盖先前输入的值。在加载到R1
和R2
之前,可以按相反顺序存储它们。因此,堆栈指针永远不会高于要使用的存储值
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}