c - 递归调用函数时出现分段错误
问题描述
我正在编写一个打印无限数字的程序。
#define false 0
#define true 1
int test(int idx) {
printf("%d\n",idx);
test(idx+1);
return 0;
}
int main() {
test(0);
return 0;
}
// Segmentation fault: 11
该程序在打印 262045 后以 segfault 结束。我了解它是由堆栈溢出引起的。
有没有什么巧妙的技巧可以让递归更深入?就像当它达到某个数字并清除堆栈时调用另一个递归函数?
我试着这样做。
#define false 0
#define true 1
int test2(int idx) {
printf("test2 here\n");
printf("%d\n",idx);
test2(idx+1);
return 0;
}
int test(int idx) {
if (idx == 262000) {
return test2(idx);
}
printf("%d\n",idx);
test(idx+1);
return 0;
}
int main() {
test(0);
return 0;
}
但是堆栈没有被清除。打印 262044 后仍有段错误。
解决方案
在第一个片段中,您遇到了 stac 溢出。
在第二种情况下,由于有符号整数溢出,它调用了 UB。
推荐阅读
- ios - 带有 UITableView 的 UITableViewCell 未显示
- angular - 无法在 Safari 中运行量角器测试
- javascript - 如何在 JavaScript 中编写两个对象之间的碰撞和反应
- javascript - Javascript:如何使变量“私有”仅用于当前的递归层?
- android - 单个事件实时数据多次发出空值将给出正确的结果
- javascript - 如何解决错误,当页面中的“onChange”未在单选按钮组件中使用时
- node.js - 如何从 Mongodb 获取数据
- javascript - 无法解析包含转义字符的 JSON 对象
- reactjs - React:为什么在onClick事件中调用函数时参数为空?
- ios - 后台状态下的 URLSession '网络连接丢失'