A stack is a last in, first out (LIFO) abstract data type and data structure. For questions about the assembly call stack, use [stack-memory], [stack-pointer], and/or [stack-frame] instead. For questions about the Haskell build tool, use [haskell-stack] instead. For questions about C++ std::stack, use [stdstack] instead.
A stack is a data structure, often used as an abstract data type (ADT) in many programming languages, to store data in a last in, first out (LIFO) manner. You could imagine it like a stack of cards. If you put a card onto the top of the stack, and then take the top card off the stack, you'll get the same card you put onto it.
Putting data onto a stack is called pushing. Taking something from a stack is called popping. Checking what's on top of a stack without removing it is called peeking.
Here is an example program:
a = new stack()
a.push(5)
b = a.peek()
print(b)
a.push(6)
b = a.pop()
print(b)
b = a.pop()
print(b)
would give the output:
5
6
5
The stack-memory is a memory region that's used to allocate space in LIFO order for the local variables of functions (and other things like return addresses and space to save call-preserved registers, all part of a function's stack-frame). It allows easy nesting of function calls (including for recursive functions). The current top-of-stack is usually tracked by a dedicated stack-pointer register. Different CPU architectures and calling conventions manage the stack differently, but it's common to push a return address as part of calling a function, building a callstack. Returning pops the return address and jumps to it, allowing a function to return to wherever it was called from.
Related tags:
- stack-overflow an error from using
push()
on a full stack, especially in stack-memory - stackunderflow an error from using
pop()
on an empty stack - buffer-overflow Writing past the end of an array in stack-memory, overwriting other things in the stack-frame, especially a return address. Not to be confused with a "stack overflow".