【问题标题】:Issues with a recursive factorial: Segmentation fault递归阶乘的问题:分段错误
【发布时间】:2020-09-12 08:16:34
【问题描述】:
.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是否有问题,但仍然得到错误,所以事实子程序内部肯定有问题。

【问题讨论】:

  • main 读取 argv[1][0] 没有检查 argc,而且你没有提供参数,所以 argv[1] 为空。
  • @prl 哈哈,我怎么这么笨?你建议我删除帖子吗?它不应该在stackoverflow上
  • @Mnkisd 更好的是:写下您的问题的答案并将其发布在此处,以便其他有相同问题的人可以从您获得的智慧中获益!

标签: recursion assembly segmentation-fault arm subroutine


【解决方案1】:

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

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

我只需要执行:

./a.out 7

例如 7 做 7 的阶乘。

【讨论】:

    猜你喜欢
    • 2019-05-26
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 2015-04-19
    • 2019-07-24
    • 2019-08-06
    相关资源
    最近更新 更多