Stack
A stack is a last-in, first-out collection. You push onto the top and pop from the top. The item that has been there the longest is the last one you see.
Detailed Explanation
The call stack is named after this structure, and so is a pile of plates. The ADT has push, pop, and usually peek / empty. In C you implement it with an array and an index, or with a linked list that inserts at the front.
The array version is a buffer and a len. push writes at data[len] and increments len. pop decrements len and returns data[len]. Capacity is the hard part. A fixed array overflows when len == cap. A growable array reallocs, typically doubling, so push is amortized O(1) and can still fail when memory is exhausted. Check that failure. Do not ignore realloc's NULL.
The list version never needs a capacity, pays a malloc per push, and pays a cache miss per pop. It is the right picture when you are describing an algorithm and the wrong one when you are pushing millions of integers.
Stacks show up as the explicit form of recursion: instead of calling dfs(node->left), you push the child and loop. They show up in expression evaluators, in undo logs, and in matching parentheses. They also show up by accident when you recurse on a structure that is a long line, and then the hardware stack is the one that overflows.
Distinguish this ADT from stack storage duration. A local variable "on the stack" is about lifetime. struct Stack is about order of access. You can allocate a struct Stack on the heap.
Popping an empty stack is a contract decision. Return an error code, abort, or document it as undefined and assert. Silent wrap of len from 0 to SIZE_MAX will then index off into space. Always test len == 0 before pop.
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Stack {
int *data;
size_t len;
size_t cap;
};
static int stack_push(struct Stack *s, int value)
{
if (s->len == s->cap) {
size_t cap = (s->cap == 0) ? 8 : s->cap * 2;
int *p = realloc(s->data, cap * sizeof *p);
if (p == NULL) {
return -1;
}
s->data = p;
s->cap = cap;
}
s->data[s->len++] = value;
return 0;
}
static int stack_pop(struct Stack *s, int *out)
{
if (s->len == 0) {
return -1;
}
*out = s->data[--s->len];
return 0;
}
int main(void)
{
struct Stack s = { NULL, 0, 0 };
if (stack_push(&s, 1) || stack_push(&s, 2)) {
free(s.data);
return 1;
}
int v;
stack_pop(&s, &v);
printf("%d\n", v); /* prints: 2 */
free(s.data);
return 0;
}Common Gotchas
`pop` on an empty stack must not decrement an unsigned `len` past zero
that wrap turns into a huge index. Check `len` first.
`realloc` failure leaves the old buffer valid
do not assign `s->data = realloc(...)` in one step if you still need to free on failure.
A stack of pointers does not own the pointees unless you say so
`free` the nodes if you stored allocated objects.
Recursion is a stack with a smaller, less visible limit
an explicit heap stack is the safe rewrite for unbounded depth.