Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

What the Heck is a Stack Overflow

GreekDataGuy
Level Up Coding
Published in
2 min readApr 23, 2020

--

Photo by Robert Anasch on Unsplash

I’m not talking about the stackoverflow you copy code from to do your job. I’m talking about what happens when I write bad recursion.

So what is a stack overflow?

According to wikipedia,

In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program.

Translation: There is a limited amount of memory (the call stack) allocated to a program. When that is exceeded (when it overflows), we call it a stack overflow.

Every time I’ve seen it, it’s been the result of infinite recursion. Recursion is when a method/function calls itself.

Sometimes recursion is intentional (ie: iterating over a graph). Sometimes it’s unintentional (a callback triggers itself).

Now let’s cause intentionally cause stack overflows in a Python, Ruby and Javascript.

Python

In your favorite code editor, switch to python and run the following.

def do_recursion():
do_recursion()
do_recursion()

This throws an error.

RecursionError: maximum recursion depth exceeded

Python throws a RecursionError when the stack gets out of bounds.

Ruby

Switch your editor to ruby and run this.

def do_recursion
do_recursion
end
do_recursion

Which results in an error.

nodepad.rb:3:in `do_recursion': stack level too deep (SystemStackError)

Ruby throws a SystemStackError when the stack level get’s too deep.

Javascript

You can run this one in the JS console in chrome.

var do_recursion = function() {
do_recursion()
}
do_recursion()

This throws an error.

Uncaught RangeError: Maximum call stack size exceeded

Javascript throws a RangeError when the stack is exceeded.

Conclusion

And that’s the real stack overflow.

In a nutshell, allocated memory is exceeded.

You won’t see it often unless you write a lot of recursive code. But it’s a good understanding to keep in your toolkit.

--

--

Write a response