我是Assembly的新手,我的目标是制作一个简单的程序,从用户那里获取两个数字,然后添加它们并显示总和。现在我无法弄清楚为什么我得到分段错误,我感觉线MOV R2,SP是罪魁祸首但是我不确定。所以,如果有人能告诉我问题是什么,并告诉我如何解决它,我将非常感激。 P.S-你能解释一下究竟什么是分段错误吗? CODE
----------------------------------------------------------
.global main
.func main
.extern scanf
main:
BL _prompt
BL _scanf
BL _scanf2
ADD R1,R1,R2
BL _printf
BL _exit
_exit:
MOV R7,#4
MOV R0,#1
MOV R2,#21
LDR R1, =exit_str
SWI 0
MOV R7,#1
SWI 0
_prompt:
MOV R7,#4
MOV R0,#1
MOV R2,#31
LDR R1,=prompt_str
SWI 0
MOV PC, LR
_printf:
MOV R4, LR
LDR R0, =printf_str
MOV R1,R1
BL printf
MOV PC, R4
_scanf:
PUSH {LR}
SUB SP, SP, #4
LDR R0, =format_str
MOV R1,SP
BL scanf
LDR R1,[SP]
ADD SP,SP,#4
POP {PC}
_scanf2:
PUSH {LR}
SUB SP, SP, #4
LDR R0, =format_str2
MOV R2,SP
BL scanf
LDR R2,[SP]
ADD SP,SP,#4
POP {PC}
.data
format_str: .asciz "%d"
format_str2: .asciz "%d"
prompt_str: .asciz "Type a number and press enter: "
printf_str: .asciz "The number entered was: %d\n"
exit_str: .ascii "Terminating program.\n"
答案 0 :(得分:0)
这个仓促的代码示例使用C函数printf,scanf和exit。代码有效但不一定符合编码标准。
每当我有多个printf和scanf项时,我喜欢使用单个_print和_scan函数,然后在调用函数之前插入参数。
硬件 - 操作系统:
$ uname -a
Linux raspberrypi 4.4.50-v7+ #970 SMP Mon Feb 20 19:18:29 GMT 2017 armv7l GNU/Linux
$ lshw
...
description: Computer
product: Raspberry Pi 2 Model B Rev 1.1
$ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 8 (jessie)"
...
代码:
.data
format_str: .asciz "%d"
// format_str2: .asciz "%d" - not required
prompt_str: .asciz "Type a number and press enter: \n"
printf_str: .asciz "The number entered was: %d\n"
exit_str: .asciz "Terminating program.\n"
total_str: .asciz "The total is %d!\n"
.text
.global main
.func main
.extern printf, scanf, exit
main:
ldr r0,=prompt_str
bl _print
ldr r0,=format_str
bl _scan
mov r10, r0 // save value
ldr r0,=printf_str
mov r1, r10
bl _print
ldr r0,=prompt_str
bl _print
ldr r0,=format_str
bl _scan
mov r11, r0 // save value
ldr r0,=printf_str
mov r1, r11
bl _print
ldr r0,=total_str
add r1, r10, r11
bl _print
ldr r0,=exit_str
bl _print
_exit:
bl exit
_print:
push {lr}
bl printf
pop {pc}
_scan:
push {lr}
sub sp,sp ,#4
mov r1, sp // place data to stack
bl scanf
ldr r0, [sp] // return data
add sp, sp, #4
pop {pc}
输出样本:
./xavier_001
Type a number and press enter:
1234
The number entered was: 1234
Type a number and press enter:
1111
The number entered was: 1111
The total is 2345!
Terminating program.