首页 > 解决方案 > 递归调用函数时出现分段错误

问题描述

我正在编写一个打印无限数字的程序。

#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 后仍有段错误。

标签: crecursionsegmentation-fault

解决方案


在第一个片段中,您遇到了 stac 溢出。

在第二种情况下,由于有符号整数溢出,它调用了 UB。


推荐阅读