递归阶乘问题:细分错误

时间:2020-09-12 08:16:34

标签: recursion assembly segmentation-fault arm subroutine

.global main
.type main%function

main:
        ldr r1,[r1,#4]    // take the argv[1]
        ldrb r1,[r1]    // take the value
        sub r1,r1,#48    // convert from char to dec
        mov r2,r1
        push {ip,lr}
        bl fact
        pop {ip,lr}
        ldr r0,=message
        b printf
fact:
        sub r2,r2,#1    // decrease the num
        push {r2,lr}    // save the num and lr
        cmp r2,#1    // compare the num with 1
        blne fact    // if the num is NOT 1, then BL the fact subroutine recursively
        pop {r2,lr}   // if the num is 1, then start to restore the nums in the stack
        mul r1,r1,r2    // and multiply them
        bx lr    // then returns
message:
        .asciz "Factorial: %d"

如果执行它,则会出现此细分错误:

$ ./a.out
Segmentation fault

可能是什么原因?我试图删除printf调用以查看printf是否存在问题,但仍然会收到错误,因此事实子例程中肯定有问题。

1 个答案:

答案 0 :(得分:2)

哈哈。我已解决问题。

我只是没有通过命令行传递任何参数,因此argv [1]基本上为空,因此存在分段错误。

我只需要执行以下操作:

./a.out 7

例如7做7的阶乘。