Stack
Just like a can of Pringles chips, it's a storage box where the last item placed on top is the first one you take out.
Definition A stack is a fundamental data structure computers use to organize information. Just like stacking books vertically inside a narrow box, newly added data sits right at the top, and whenever you remove data, you always take the newest item from the top first.
Think of a Stack of Plates at a Buffet
When you visit a buffet, clean plates are stacked tall in neat piles. Whenever fresh plates arrive, staff place them right on top. And when guests take a plate, they naturally grab the one on top rather than risking a mess by yanking one from the bottom.
In computer science, this same pile-like structure is called a stack. The last piece of data to enter is always the first one to leave. Programmers call this principle Last In, First Out (LIFO).
Stacks power many features we use every day. Your web browser's Back button and word processors' Undo shortcut (Ctrl+Z or Cmd+Z) are classic examples.
How Computers Remember What to Do Next
Imagine you are studying when a friend calls you. While chatting, the doorbell rings with a package delivery. Naturally, you answer the door first, then finish your phone call, and finally return to your studies.
Computers handle multitasking in the exact same order when executing functions (blocks of code). Whenever one function calls another, the computer saves its current spot onto a stack before jumping to the new task. This dedicated record keeper is known as the call stack.
Once a task finishes, the computer pops the top record off the stack and smoothly resumes the previous task. Thanks to this stack, complex sequences of actions unwind in perfect reverse order without getting lost.
When the Box Overflows
In a stack, adding items (push) and removing them (pop) only ever happen at the very top. Because the computer only needs to track the top position, operations are blazingly fast.
However, stack memory is not infinite. If a bug causes a function to call itself endlessly in a runaway loop (infinite recursion), records pile up until they burst out of their allocated memory.
This crash is called a stack overflow. It is so famous in programming that the world's most popular developer Q&A website is named after it! When this happens, the operating system halts the program to protect system memory.
π€ Common misconceptions
You can easily pluck out items from the middle of a stack whenever you want.
A stack only allows access to the top item. To reach items in the middle or bottom, you must first remove everything stacked on top of them.
π§Ί Where you meet it
A Last In, First Out (LIFO) storage system where the most recently added item is always the first to be retrieved.