使用Scanf ARM组件进行分段故障

时间:2017-09-03 16:47:21

标签: assembly arm printf scanf

我是集会新手,过去几天在互联网上寻求帮助,但无济于事。

.data

format: .asciz "%s"
string: .asciz "Output: %s\n"

prompt: .asciz ">"

.text
.global main
.main:

    ldr r0, addr_prompt     /*loading address of prompt message in r0*/
    bl printf               /*calling printf*/   

    ldr r0, addr_format     /*loading first parameter of scanf*/
    ldr r1, addr_string     /*loading second parameter of scanf*/
    bl scanf                /*calling scanf*/

    /*below I am trying to print out the user 
    input from scanf*/

    ldr r1, [r1]            
    bl printf

    mov r7, #1
    swi 0

addr_prompt: .word prompt
addr_format: .word format
addr_string: .word string

运行时,会出现"分段错误"错误。有人可以告诉我我做错了什么,非常感谢任何帮助。

编辑:根据建议添加注释代码和修复版本错误(scanf - > bl scanf)

1 个答案:

答案 0 :(得分:0)

需要缓冲区/存储空间来存储输入数据。

.data

format: .asciz "%s"

string: .asciz "Output: %s\n"
prompt: .asciz ">"

storage: .space 80          @ --- added buffer

.text
.global main
main:                       @ --- removed .

    ldr r0, addr_prompt     /*loading address of prompt message in r0*/
    bl printf               /*calling printf*/

    ldr r0, addr_format     /*loading first parameter of scanf*/
    ldr r1, addr_storage    @ --- location to write data from input
    bl scanf                /*calling scanf*/

    /*below I am trying to print out the user
    input from scanf*/

    ldr r1, addr_storage    @ --- data location
    ldr r0, addr_string     @ --- printf format
    bl printf

    mov r0, #0              @ --- good return code
    mov r7, #1
    swi 0

addr_prompt: .word prompt
addr_format: .word format
addr_string: .word string
addr_storage: .word storage @ --- address of buffer

Raspberry Pi Raspbian的输出:

as -o printf10.o printf10.s
gcc -o printf10 printf10.o

./printf10; echo $?
>Hello
Output: Hello
0