0

How can I run the following program in python 2.7.3

import sys
sys.setrecursionlimit(2 ** 20)
def f(x):
    if (x==0): return 0
    else: return f(x-1)+1
print f(200000)

This code receives segmentation fault in Ubuntu.

2
  • It appears that you're overrunning your stack. You can increase your recursion limit, but that doesn't increase your stack size. Try rewriting it as a loop instead.
    – N_A
    Apr 8, 2013 at 14:36
  • See stackoverflow.com/a/2918118/90308
    – FogleBird
    Apr 8, 2013 at 14:36

1 Answer 1

2

The Python interpreter runs out of stack space. Like any other process in the same situation, it is getting killed by the operating system.

You could try increasing the OS stack size limit (ulimit -c).

A better approach might be to rewrite your code so that it does not require recursion this deep (your particular example can be trivially converted into iteration).

2
  • My code is an example which I know about this problem. Original code is hard for rewriting without recursion. ulimit -c 5000000 But I get SF again. Apr 8, 2013 at 14:41
  • 2
    It should be "ulimit -s" ss64.com/bash/ulimit.html. "ulimit -a" should give you all the system defaults and the necessary flags when used to set these values.
    – Ifthikhan
    Apr 8, 2013 at 14:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.