Make Python stack overflow and core dump
All you need is a recursive function. I’m using Python 3.6.5, enjoy!
Python limits the call stack depth to prevent infinite recursion and an overflow of the C stack. sys.getrecursionlimit() and sys.setrecursionlimit(limit) can get and set this limit.
import sysdef recursive_sum(x):
return x + recursive_sum(x - 1) if x > 0 else 0print(f'Default sys.getrecursionlimit()={sys.getrecursionlimit()}')
print(f'recursive_sum(100)={recursive_sum(100)}')
print(f'recursive_sum(1000)={recursive_sum(1000)}')
This code will exhaust the default call stack depth and raise a RecursionError like this:
~$ python3 test.py
Default sys.getrecursionlimit()=1000
recursive_sum(100)=5050
Traceback (most recent call last):
File "test.py", line 8, in <module>
print(f'recursive_sum(1000)={recursive_sum(1000)}')
File "test.py", line 4, in recursive_sum
return x + recursive_sum(x - 1) if x > 0 else 0
File "test.py", line 4, in recursive_sum
return x + recursive_sum(x - 1) if x > 0 else 0
File "test.py", line 4, in recursive_sum
return x + recursive_sum(x - 1) if x > 0 else 0
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded in comparisonLet’s bump up the limit to an unrealistic one and see what happens.
import sysdef recursive_sum(x):
return x + recursive_sum(x - 1) if x > 0 else 0print('Bumping up recursion limit...')
sys.setrecursionlimit(1000000000)
print(f'sys.getrecursionlimit()={sys.getrecursionlimit()}')print(f'recursive_sum(100)={recursive_sum(100)}')
print(f'recursive_sum(1000)={recursive_sum(1000)}')
print(f'recursive_sum(10000000)={recursive_sum(10000000)}')
And run it:
Bumping up recursion limit...
sys.getrecursionlimit()=1000000000
recursive_sum(100)=5050
recursive_sum(1000)=500500
Segmentation fault (core dumped)Now we can get the sum from 0 to 1000, but for the sum from 0 to 10000000, there’s segmentation fault, which is caused by accessing memory that “does not belong to you.” The iterative version has no such memory overhead:
>>> sum(range(10000000))
49999995000000To conclude, it’s better to convert a recursive solution to an iterative solution to save memory, or bump up the default recursion limit, but be reasonable with this limit.