Make Python stack overflow and core dump

Chao Ren
Chao Ren
Sep 2, 2018 · 2 min read

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 0
print(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 comparison

Let’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 0
print('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))
49999995000000

To 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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade