What is a stack overflow?
Computer science university teaching assistant. Taught 200+ students so far 🎓
Although this question is marked as general, I assume you mean this question in the context of computer programming. A stack, in this context, is the last in, first out buffer you place data while your program runs. Last in, first out (LIFO) means that the last thing you put in is always the first thing you get back out. Adding an item to the stack is called pushing, taking an item from the stack is called popping. If you push 2 items on the stack, 'A' and then 'B', then the first thing you pop off the stack will be 'B', and the next thing is 'A'. Think of a stack of plates. If you add a plate to the stack, it is at the bottom. If you add a second plate it is at the top. You must first remove (pop) the second plate in order to pop the first one. When you call a function in your code, the next instruction after the function call is stored on the stack, and any storage space that might be overwritten by the function call. The function you call might use up more stack for its own local variables. When it's done, it frees up the local variable stack space it used, then returns to the previous function. A stack overflow is when you've used up more memory for the stack than your program was supposed to use. Many programmers make this mistake by calling function A that then calls function B, that then calls function C, that then calls function A. It might work most of the time, but just once the wrong input will cause it to go in that circle forever until the computer recognizes that the stack is overblown. Recursive functions are also a cause for this, but if you're writing recursively (ie, your function calls itself) then you need to be aware of this and use static/global variables to prevent infinite recursion. You should look at your call graph (a tree structure that shows from your main method what each function calls) to see how deep your function calls go, and to detect cycles and recursion that are not intended. This answer was adapted from an answer here (from a website called stackoverflow!): https://stackoverflow.com/questions/26158/how-does-a-stack-overflow-occur-and-how-do-you-prevent-it
Fares also answered
Find me a tutor
We take your privacy seriously. View our policy.