Sub topic 12
Function calls and the call stack
This chapter assumes you know basic C functions, how pointers and pass by value work (covered earlier in this tutorial), and what automatic and static storage mean. It explains what the machine does when one function calls another. GATE questions on output prediction, lifetime and recursion all depend on this model.
Why a stack
Calls nest. If main calls a, and a calls b, then b must finish first, then a, then main. The most recently started call is always the first to finish. That is last in, first out (LIFO) order, which is how a stack works. The runtime keeps a region of memory called the call stack and adds one block to it for each active call.
The C standard never uses the word "stack". It only defines automatic storage duration, and nearly every implementation realizes that with a stack. The details below describe typical implementations, so treat them as a model rather than as guarantees.
What a stack frame holds
Each call creates a stack frame (also called an activation record). A typical frame holds:
- The return address, which is where execution resumes in the caller.
- The saved frame pointer, which lets the callee restore the caller's frame on exit.
- The parameters, if they are not passed in registers.
- The local variables with automatic storage.
- Saved registers and temporary values.
On most machines the stack grows toward lower addresses. A function called later therefore usually has locals at lower addresses than its caller. The standard does not promise this, so a GATE question that depends on it will say so.
Tracing a call chain
#include <stdio.h>
int square(int x) {
int r = x * x;
return r;
}
int sum_squares(int a, int b) {
int s = square(a) + square(b);
return s;
}
int main(void) {
int total = sum_squares(2, 3);
printf("%d\n", total);
return 0;
}This prints 13. At the deepest point the stack holds three frames: main, sum_squares and square. When square returns, its frame is removed and the result goes back to the caller, usually in a register. The two calls to square reuse the same stack space one after the other. They never exist at the same time.
Order of output
Print statements before and after a call show the LIFO order directly.
#include <stdio.h>
void c(void) { printf("c "); }
void b(void) {
printf("b1 ");
c();
printf("b2 ");
}
void a(void) {
printf("a1 ");
b();
printf("a2 ");
}
int main(void) {
a();
printf("\n");
return 0;
}The output is a1 b1 c b2 a2. Statements after a call run only when the callee's frame has been popped. The same pattern drives recursive output questions in later chapters.
Each call gets its own locals
Every call creates fresh copies of parameters and automatic variables. Changing them never affects the caller's variables, because C passes arguments by value. A static local is different. It lives in the data segment, not in the frame, so it keeps its value between calls.
#include <stdio.h>
int counter_auto(void) {
int n = 0;
n++;
return n;
}
int counter_static(void) {
static int n = 0;
n++;
return n;
}
int main(void) {
int a = counter_auto();
int b = counter_auto();
int c = counter_static();
int d = counter_static();
printf("%d %d %d %d\n", a, b, c, d);
return 0;
}This prints 1 1 1 2. The automatic n is recreated and reinitialized on every call. The static n is initialized once, before the program starts, and the initializer is not run again.
Where each kind of object lives:
| Object | Typical location | Lifetime |
|---|---|---|
| Parameters and automatic locals | Stack frame | Until the function returns |
| `static` locals and globals | Data segment | Whole program run |
| `malloc`ed blocks | Heap | Until `free` |
| Machine code | Code segment | Whole program run |
Locals die with the frame
After a function returns, its frame's memory is free to be reused by the next call. A pointer into that frame is then a dangling pointer. The classic mistake is a function that returns &r where r is an automatic local. Using that pointer is undefined behavior. It may appear to work until the next call overwrites the memory.
There are three safe alternatives. Return the value itself, let the caller supply the storage, or use static or heap storage.
#include <stdio.h>
void make_pair(int *lo, int *hi, int a, int b) {
*lo = a < b ? a : b;
*hi = a < b ? b : a;
}
int main(void) {
int lo, hi;
make_pair(&lo, &hi, 9, 4);
printf("%d %d\n", lo, hi);
return 0;
}This prints 4 9. The callee writes into variables that live in the caller's frame, which is still active, so the addresses stay valid.
Argument evaluation order
The standard does not specify the order in which a function's arguments are evaluated. In f(g(), h()), either call may run first. If the arguments modify the same variable without sequencing, as in printf("%d %d", i++, i++), the behavior is undefined. Questions that depend on a particular order are either asking you to spot this trap or are badly posed.
Stack depth and overflow
The stack has a fixed size, commonly about 8 MB on Linux and 1 MB on Windows by default. Two things can exhaust it:
- Very deep call chains. Recursion with no base case, or with a depth in the millions, adds one frame per call until the program crashes.
- Large automatic arrays, such as
int buf[10000000];inside a function.
The crash is called stack overflow. The cure is a smaller depth, an iterative version, or heap storage for large data. Stack depth is part of the space cost of recursion, which a later chapter measures alongside time.
Summary of the model
- Each call pushes a frame holding the return address, parameters and locals.
- Each return pops the frame, and the most recent call finishes first.
- Automatic variables are per call and are gone after return. Static variables persist.
- Pointers to a returned frame dangle.
- Argument evaluation order is unspecified.
Exercise
In the program below, what is printed, and what is the largest number of frames on the stack at one time (counting main)? #include <stdio.h> void inc(int x) { x++; } void twice(int y) { inc(y); inc(y); } int main(void) { int v = 5; twice(v); printf("%d\n", v); return 0; }
Show answer
It prints 5. Arguments are passed by value, so inc changes only its own copy of x, and twice changes nothing in main. The deepest chain is main, twice, inc, so the maximum is 3 frames. The two inc calls run one after the other, so they never overlap.
Exercise
A function declares static int hits = 0;, then does hits++ and returns hits. It is called three times in a row from main. What are the three return values, and what would they be if static were removed?
Show answer
With static they are 1, 2, 3, because the single variable persists in the data segment and its initializer runs once. Without static, hits is a fresh automatic variable set to 0 on each call, so every call returns 1.