首页 > 解决方案 > 递归阶乘的问题:分段错误

问题描述

.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 是否有问题,但仍然得到错误,所以事实子程序内部肯定有问题。

标签: recursionassemblysegmentation-faultarmsubroutine

解决方案


哈哈。我解决了这个问题。

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

我只需要执行:

./a.out 7

例如 7 做 7 的阶乘。


推荐阅读