recursion - 递归阶乘的问题:分段错误
问题描述
.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 是否有问题,但仍然得到错误,所以事实子程序内部肯定有问题。
解决方案
哈哈。我解决了这个问题。
我只是没有通过命令行传递任何参数,所以基本上 argv[1] 为空,因此是分段错误。
我只需要执行:
./a.out 7
例如 7 做 7 的阶乘。
推荐阅读
- haskell - 如何传递一个空白页面?
- javascript - 在angularjs中接收序列化对象作为查询字符串参数
- ios - 多线程违规 剩下的就是荣誉(失败)
- mysql - mysql IF-Statement 的问题:提供更改的值
- android - 安卓通知不显示
- c# - 使用复杂命令渲染 Powershell 输出
- assembly - 如何解决二元炸弹实验室的第 4 阶段
- python - 如何修复'ValueError:DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。何时使用 &
- java - 试图划分颜色来画彩虹甜甜圈
- powershell - Get-Content 使用不同的 Get-ChildItem 产品