Overflowing the stack in Python

So Python doesn’t really have a “stack”… in most cases it’s heap memory of some sort. So is it possible to cause a stack overflow? Sure – but it’s not as easy as in C. Here’s a piece of code that places a set within a set, to create what is essentially a deeply nested set.

def deeplyNestedSet(depth):
    setA = {'a'}
    for i in xrange(depth):
        setB = {}
        setB[i] = setA
        setA = setB
    return setB

print deeplyNestedSet(10)

Here is the output:

{9: {8: {7: {6: {5: {4: {3: {2: {1: {0: set([‘a’])}}}}}}}}}}

Now changing the 10 to 100000 causes the program to break a little over half-way through.

{47776: Segmentation fault: 11

Turns out it’s more of an issue with the print statement than the actual code itself.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s