Sub topic 1
How a Running Program Uses Memory
This chapter assumes basic C-style functions and recursion, stacks, linked lists, graphs, and introductory parse trees. You should also know set operations such as union and difference.
Prerequisites
- Functions, parameters, local variables, and recursion
- Stack and heap data structures
- Basic understanding of addresses and pointers
The Runtime Memory Layout
A compiler translates source code into machine instructions. When the program runs, the operating system gives it a virtual address space. This space is commonly divided into regions with different purposes.
| Region | Typical contents | Lifetime |
|---|---|---|
| Code | Executable instructions | Entire program |
| Static data | Global and static variables | Entire program |
| Heap | Dynamically allocated objects | Until released or collected |
| Stack | Function calls and local data | During calls |
The code region is usually read-only. Static data contains variables whose lifetime lasts for the entire execution. The heap supports objects created at runtime, such as those created by malloc. The stack records active function calls.
#include <stdlib.h>
int total = 10; // static data
int add_one(int value) { // value and result use the stack
int result = value + 1;
return result;
}
int main(void) {
int *p = malloc(sizeof *p); // allocated object uses the heap
*p = add_one(total);
free(p);
return 0;
}The exact layout depends on the operating system and compiler. The important model is that different kinds of data have different lifetimes and management rules.
Activation Records and the Control Stack
An activation record, also called a stack frame, stores information for one active function call. A frame commonly contains:
- Parameters and return-value information
- Local variables
- Temporary values
- The return address
- A saved frame pointer or stack pointer
- Links needed to access other scopes
The control stack is the sequence of activation records for calls that have started but not returned. The newest call is at the top. A function's local variables normally disappear when its frame is removed.
Consider recursion:
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
int main(void) {
return fact(3);
}After main calls fact(3), the stack grows as follows:
mainfact(3)fact(2)fact(1)
The maximum stack depth is four frames, including main. Each recursive call has a separate copy of n. When fact(1) returns, its frame is removed. Control resumes in fact(2), which multiplies its saved value by the returned result.
Stack exhaustion occurs when calls keep creating frames faster than they return. Deep recursion, large local arrays, or both can cause this failure.
Exercise
What is the maximum number of active frames when main calls fact(4) in the example above?
Show answer
Five: one frame for main and four frames for fact(4), fact(3), fact(2), and fact(1).