0

I'm writing a program that prints infinite numbers.

#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

This program ended with a segfault after printing 262045. I understand it is caused by stack overflow.

Is there any clever trick that can make the recursion go deeper? Like calling another recursive function when it reaches a certain number and clears the stack?

I tried doing this.

#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;
}

But the stack is not cleared. There is still a segfault after printing 262044.

qwerty
  • 1
  • 1
  • 2
    You have reached your stack size limit. Of course, it makes no sense to use recursion for something like this (for that very reason), but if you really want to, the best you can do is increase your stack size limit. But that will only buy you so much before you encounter the problem again. – Tom Karzes Nov 13 '20 at 07:15
  • 2
    A very deep recursion would cause stackoverflow. The second one is not a recursion. – Karthick Nov 13 '20 at 07:16
  • Looks like a XY problem. Why do you think you need a deeper recursion or stack clearing (problem Y). What is your original problem (X) that you think you can solve by (Y)? – mbaitoff Nov 14 '20 at 17:36

1 Answers1

0

In the first snippet, you're hitting a stac overflow.

In the second case, it invokes UB because of signed integer overflow.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261