python segfault

Chris Kaynor ckaynor at zindagigames.com
Tue Mar 27 18:40:04 EDT 2012


On Tue, Mar 27, 2012 at 3:27 PM, Michael Poeltl
<michael.poeltl at univie.ac.at> wrote:
> hi,
>
> can anybody tell why this 'little stupid *thing* of code' let's python-3.2.2, 2.6.X or python 2.7.2 segfault?
>
>>> def get_steps2(pos=0, steps=0):
> ...     if steps == 0:
> ...         pos = random.randint(-1,1)
> ...     if pos == 0:
> ...         return steps
> ...     steps += 2
> ...     pos += random.randint(-1,1)
> ...     return get_steps2(pos,steps)
> ...
>>>> import random, sys
>>>> sys.setrecursionlimit(100000)

If you remove this setrecursionlimit, it will throw an exception. The
issue is that your code is overflowing the C stack by trying to make
too many calls. The Python recursion limit prevents this by turning
such cases into Python exceptions prior to the stack overflow.

As your recursion is based on a random number generator, all you need
is a sequence of random numbers that is unbalanced between -1 and 1
results for 1000-3000 calls (the exact number will vary from os,
compiler, maybe machine, etc), which is not too unlikely to occur.



More information about the Python-list mailing list