3

Can python have a stack overflow error?
Recently I was just letting my mind wander when I came across the question: "can python get the stack overflow error? Does anyone have any answers?

I searched for the answer but only found java answers. I have used java but its just not my question:

  1. What is a StackOverflowError?
  2. https://rollbar.com/blog/how-to-fix-java-lang-stackoverflowerror-in-java/

My Reasoning
I initially thought no because python just... works most of the time (like passing an int for a string). It also doesn't have stacks (to my knowledge). But I wasn't sure. Here I am.

a1cd
  • 17,884
  • 4
  • 8
  • 28
  • 3
    Of course it has a stack, that's how function calls are implemented. If you recurse too deeply you get a stack overflow error. – Barmar Oct 26 '21 at 22:37
  • 2
    My brain just connected why stack trace is called stack trace... – a1cd Oct 26 '21 at 22:41

3 Answers3

5

Sure it can

the following code will cause a seg fault:

import sys
sys.setrecursionlimit(10_000_000)

def foo():
    foo()

On Mac OS, this throws:

Segmentation fault: 11

Which is caused by a stack overflow.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
2

You can, if your recursion limit is too high:

def foo():
    return foo()


>>> foo()

Result:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  .......
  File "<stdin>", line 2, in foo
RuntimeError: maximum recursion depth exceeded
>>> 

The default recursion limit is 10**3 (verifiable via sys.getrecursionlimit), but you can change it using sys.setrecursionlimit:

import sys
sys.setrecursionlimit(10**8)

def foo():
    foo()

but doing so could be dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.

Community
  • 1
  • 1
krmogi
  • 2,588
  • 1
  • 10
  • 26
0

By default, Python's recursion limit is 10**3, theoretically if you were to pass this then you would be given a RecursionError.

You can even reduce the recursion limit using setrecursionlimit() to make this happen more quickly.

Skully
  • 2,882
  • 3
  • 20
  • 31
  • You are the second to mention `10**4` as the default limit, however I suspect it is an implementation detail. I get `10**3` as the default in 64-bit CPython 3.8.5 on 64-bit Win 11 – DeepSpace Oct 26 '21 at 22:47
  • 1
    Your right, the default is actually 1000. (Checked with `sys.getrecursionlimit()`) – Skully Oct 26 '21 at 22:53