The stack holds a function’s local data
In C, the stack is where local variables and function call data are kept. Most C implementations do this with a region of memory that grows and shrinks as functions are called and return. The C standard calls this automatic storage duration. You don’t allocate or free stack memory yourself: a variable gets its space when its function starts, and that space goes away when the function ends.
How a function call uses the stack
Each call creates a stack frame. A frame holds the function’s parameters and local variables. Here is a small C program with three functions:
#include <stdio.h>
void inner(int depth)
{
int local = depth * 10; /* lives in inner's stack frame */
printf("inner: depth=%d local=%d\n", depth, local);
}
void outer(void)
{
int a = 1; /* lives in outer's stack frame */
inner(2);
printf("outer: a=%d\n", a);
}
int main(void)
{
int x = 5; /* lives in main's stack frame */
outer();
printf("main: x=%d\n", x);
return 0;
}
The program prints:
inner: depth=2 local=20
outer: a=1
main: x=5
Here is what happens, step by step:
mainstarts, and its frame holdsx.maincallsouter, and a new frame foroutergoes on top. It holdsa.outercallsinner(2), and a third frame goes on top. It holdsdepthandlocal, which is 20.innerprints its values and returns. Its frame is removed, solocalno longer exists.outerprintsaand returns. Its frame is removed.mainprintsxand returns.
Why it’s called last in, first out
The most recent call is the first one to return, and its frame is the top frame, so it is removed first. That is last in, first out, or LIFO. Think of a stack of plates: you put new plates on the top, and you take plates off the top.
Two things to watch for
Returning the address of a local variable. The memory for a local variable disappears when its function returns, so a pointer to that variable points to memory that is no longer valid.
int *make_number(void)
{
int value = 5;
return &value; /* value ends when make_number returns */
}
Using the returned pointer is undefined behavior. Most compilers warn about this code, so turn on compiler warnings and read them.
Stack overflow. The stack has a size limit. A function that calls itself without a stop condition adds a frame on every call, and eventually the stack runs out. Very large local arrays can cause the same problem. Overflowing the stack usually crashes the program, often with a segmentation fault.
Where malloc memory lives
Memory from malloc is not on the stack. It lives on the heap until you call free. Because you release it by hand, heap memory follows different rules for lifetime, speed and size. The contrast is laid out in the guide to c heap vs stack.