You can cause a stack overflow quite easily in python, as in any other language, by building an infinately recursive funcion. This is easier in python as it doesn't actually have to do anything at all other than be recursive.

>>> def foo():
...     return foo()
... 

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

As for the heap, that is managed by a garbage collector. You can allocate lots of objects and eventually run out of heap space and Python will raise a MemoryError, but it's going to take a fair amount of time. You actually did that with your 'stack overflow' example in the question. You stored a reference to a string on the stack, this string took up all the free memory available to the process. As a rule of thumb, Python stores a reference to a heap structure on the stack for any value that it can't guarantee the size of.

As for how it all works, from the fist example you can see that python has a built-in limit to the depth of the call stack that it will not exceed. The amount of memory available for heap space is defined by the OS however and will depend upon many factors.

These are should be the appropriate parts of the python docs for infomation on the errors themselves:

  • http://docs.python.org/release/3.2.3/library/exceptions.html#RuntimeError
  • http://docs.python.org/release/3.2.3/library/exceptions.html#MemoryError
Answer from Will on Stack Overflow
🌐
Python
peps.python.org › pep-0651
PEP 651 – Robust Stack Overflow Handling | peps.python.org
This PEP proposes that Python should treat machine stack overflow differently from runaway recursion.
🌐
Reddit
reddit.com › r/learnpython › python stack overflow
r/learnpython on Reddit: Python Stack Overflow
August 13, 2021 -

Hello! I am new to python. I created a script/bot, and its function is work until closed.

That bot has a main() function that one way or another calls itself after a 1 minute timer.

After some time i noticed that it crashed and closed Tested again but now in Visual Studio Code and after 18 hours it crashed again with fatal error stack overflow.

Went in and created a separate script with a main function calling itself and after 1035 loops it caused stack overflow. Now 1035*1minute is about 18 hours.

How can i create an infinite script without causing stack overflow?

Thanks!

Discussions

How to cause stack overflow and heap overflow in python - Stack Overflow
I am trying to understand how python manages stack and heap. So I wanted to do some "bad" programming and cause a stack overflow and heap overflow. What I don't understand is why strings for example go to stack while all others go to heap. Is it just agreement of the designers? More on stackoverflow.com
🌐 stackoverflow.com
Newest 'python' Questions - Stack Overflow
Supports Claude Code, Cursor, Codex, Windsurf and more. Explore Stack Overflow for Agents ... Why intent prediction needs more than an... ... How do Trump v. Slaughter and Trump v. More on stackoverflow.com
🌐 stackoverflow.com
5 days ago
Am i still a python programmer if use stack overflow a lot and finish projects?
You'd be a terrible developer if you didn't. More on reddit.com
🌐 r/learnpython
156
410
May 1, 2020
Highest scored 'python' questions - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... The 2026 Annual Developer Survey is live— take the Survey today! Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... What functionality does the yield keyword in Python ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
martinxpn.medium.com › what-is-stack-overflow-really-40-100-days-of-python-e5e129416d33
What is Stack Overflow Really? (40/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - As the stack memory becomes exhausted, a stack overflow error will occur, causing the program to crash or produce unexpected results. This error is especially common in programming languages that use a stack-based model for function calls and ...
Top answer
1 of 2
8

You can cause a stack overflow quite easily in python, as in any other language, by building an infinately recursive funcion. This is easier in python as it doesn't actually have to do anything at all other than be recursive.

>>> def foo():
...     return foo()
... 

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

As for the heap, that is managed by a garbage collector. You can allocate lots of objects and eventually run out of heap space and Python will raise a MemoryError, but it's going to take a fair amount of time. You actually did that with your 'stack overflow' example in the question. You stored a reference to a string on the stack, this string took up all the free memory available to the process. As a rule of thumb, Python stores a reference to a heap structure on the stack for any value that it can't guarantee the size of.

As for how it all works, from the fist example you can see that python has a built-in limit to the depth of the call stack that it will not exceed. The amount of memory available for heap space is defined by the OS however and will depend upon many factors.

These are should be the appropriate parts of the python docs for infomation on the errors themselves:

  • http://docs.python.org/release/3.2.3/library/exceptions.html#RuntimeError
  • http://docs.python.org/release/3.2.3/library/exceptions.html#MemoryError
2 of 2
6

please correct me if wrong:

As far as I know, when it comes to actual stack implementation, the python stack (in the default distribution) is actually based in the heap memory (memory allocated with malloc). So you cannot cause the stack overflow, but you can run out of memory. The computer slowdown you seen is because memory is being swapped to disk, very slow procedure.

generally, you have no idea how the interpreted/byte-compiled language implements its stack, but most like it is not implemented in the stack memory, so you cannot cause stack overflow. it is possible to implement Python using alloca, but why?

Cf. CPython - Internally, what is stored on the stack and heap?

Try the same experiment with compiled language, C++, Fortran, etc. which compiles to machine code.

🌐
Stack Overflow
stackoverflow.com › questions › tagged › python
Newest 'python' Questions - Stack Overflow
5 days ago - I have a Python script that connects to BigQuery, and can pull down data from google.cloud import bigquery import os os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "XXXXX.json" #file ... ... I made a little multiplication table game with a multiplayer mode. For the future I have started to decouple the logic and the output, so I can easily (easier) add new math tasks like addition, ... ... Help me join Stack Overflow for Agents here.
🌐
Stack Overflow
stackoverflow.blog › python
python - Stack Overflow
April 30, 2026 - In this session, we'll bypass all that math by using Python loops to simulate the CLT. ... We discuss ten tips for preventing runaway code when a spaceship is on the line. ... We're excited to share the results of our 10th annual developer survey! 65,000 developers shared their thoughts on the state of software today. ... BulletinCommunitydev opsdev surveydev survey 2020developer surveyhello - old friendovertimepythonremote workruststack overflowstack overflow dev surveyStackoverflowStackoverflowtypescript Show more
🌐
Stack Overflow
stackoverflow.blog › 2021 › 07 › 14 › getting-started-with-python
Getting started with... Python - Stack Overflow
July 14, 2021 - Although Python has been around since the 1.0 release in 1991, its usage has ballooned in recent years. Indeed, as our former data scientist David Robinson noted, since 2012, it has risen above the five other major languages (C++, PHP, Java, JavaScript and C#) in usage as estimated by the number of Stack Overflow question views per month.
Find elsewhere
🌐
Stack Overflow
stackoverflow.blog › 2017 › 09 › 14 › python-growing-quickly
Why is Python Growing So Quickly? - Stack Overflow
September 14, 2017 - ... We recently showed that, based on Stack Overflow question visits, Python has a claim to being the fastest-growing major programming language, and that it has become the most visited tag on Stack Overflow within high-income countries.
🌐
ScienceDirect
sciencedirect.com › science › article › abs › pii › S2590118425000267
Python’s evolution on Stack Overflow: An empirical analysis of topic trends - ScienceDirect
June 12, 2025 - With the rapid development of information technology and changing programming practices, the demand for programming discussions on online Q&A platforms is growing. This study analyzes over two million Python-related posts on Stack Overflow to identify core topics and challenges over fifteen years.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › python
Highest scored 'python' questions - Stack Overflow
d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(key, 'corresponds to', d[key]) How does Python recognize that it needs only to read the key from the dictionary? Is key a special keyword, or is ... ... I have a pandas dataframe, df: c1 c2 0 10 100 1 11 110 2 12 120 How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name ... ... Help me join Stack Overflow for Agents here.
🌐
Plain English
plainenglish.io › blog › 30-highest-voted-python-questions-on-stack-overflow
30 Highest-Voted Python Questions on Stack Overflow
In this article, I am compiling the highest-voted Python-related questions on StackOverflow. Let's check out how deeply you know Python programming.
Starred by 3.7K users
Forked by 130 users
Languages: Python
🌐
CodeRivers
coderivers.org › blog › python-stackoverflow
Python Stack Overflow: A Comprehensive Guide - CodeRivers
February 22, 2026 - Explain that the slicing operation [::-1] reverses the list in Python. Use Descriptive Keywords: When searching for solutions on Stack Overflow, use relevant keywords.
🌐
CodeRivers
coderivers.org › blog › stack-overflow-python
Demystifying Stack Overflow in Python - CodeRivers
February 22, 2026 - If the stack grows too large, for example, due to a large number of nested function calls or infinite recursion, a stack overflow error occurs. The Python interpreter raises a RecursionError with a message like "maximum recursion depth exceeded" in the case of recursive functions causing the ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › auto-search-stackoverflow-for-errors-in-code-using-python
Auto Search StackOverflow for Errors in Code using Python - GeeksforGeeks
July 23, 2025 - Ever faced great difficulty in copying the error you're stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer? Worry Not, Here's the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on Stack Overflow, and opens up the few tabs related to our error that were previously been answered also.
🌐
Stack Overflow
stackoverflow.com › questions › 18754276 › python-for-beginners
Python for beginners - Stack Overflow
Python programming: I need to write a program that takes two inputs of military time. For example,(0900,1700) and output the time differences of the two input in numbers in hours, minutes ex: pr...
🌐
Stack Overflow
stackoverflow.blog › 2017 › 09 › 06 › incredible-growth-python
The Incredible Growth of Python - Stack Overflow
September 6, 2017 - We have data on Stack Overflow question views going back to late 2011, and in this time period we can consider the growth of Python relative to five other major programming languages. (Note that this is therefore a shorter time scale than the Trends tool, which goes back to 2008).
🌐
Stack Overflow
stackoverflow.blog › newsletter › issue-229-python-for-everyone
Issue 229: Python for everyone - Stack Overflow
May 22, 2024 - On this episode: Al Sweigart is a software developer, developer advocate, and author of ten Python books. He tells Ben and Ryan why he’s such a fan of the language, why it’s a great programming language for beginners, and how it became the default for so many data science and backend AI projects. We're excited to announce the general availability of OverflowAI to Stack Overflow for Teams!