Sub topic 1
How a running program uses memory
This chapter describes how a compiled program organizes memory while it runs. Later chapters build on it: activation records, scope, parameter passing, and the heap.
Prerequisites
This chapter assumes you know:
- Basic C-style programming, including functions and recursion.
- Stacks and linked lists as data structures.
- That a compiler translates source code into machine code before the program runs.
The four storage areas
When the operating system starts a compiled program, the program gets a block of logical address space. The compiler decides how this space is divided. A typical layout has four areas.
- Code (text). The machine instructions. Its size is fixed at compile time and it is usually read-only.
- Static data. Global variables,
staticvariables and constants. Their size is known at compile time, and they exist for the whole run. - Heap. Memory requested while the program runs, for example with
mallocornew. It lives until the program frees it, or until a garbage collector reclaims it. - Stack. The control stack holds one activation record for each active procedure call. It grows when a procedure is called and shrinks when the procedure returns.
The stack and the heap sit at opposite ends of the free space and grow toward each other. This lets both use the space that is left, without fixing a split in advance.
Some diagrams draw the stack at the top and the heap at the bottom. The direction of growth is a convention, so do not memorize a fixed picture. Memorize which areas have a size known at compile time (code and static data) and which change at run time (heap and stack).
Static and dynamic allocation
The compiler uses two kinds of allocation.
- Static allocation fixes an address at compile time. It is used for globals and
staticvariables. It cannot support recursion for local variables, because each recursive call needs its own copy. - Dynamic allocation picks the address at run time. It has two forms: stack allocation for local variables of procedures, and heap allocation for data that must outlive the call that created it.
A language that allows recursion needs stack allocation for locals. Early Fortran had no recursion and used static allocation for everything.
Why locals go on the stack
Procedure calls follow a last-in, first-out order. If main calls f and f calls g, then g must finish before f does, and f before main. A stack matches this pattern. Local variables are created when a call begins and are no longer needed when it ends, so their storage is freed by moving the stack top back.
A recursive call gets a new activation record, so each call has its own copy of its locals and parameters. The next chapter looks at this record in detail.
Where each variable lives
Consider this C program.
#include <stdio.h>
#include <stdlib.h>
int counter = 0; /* static data */
const char *msg = "hello"; /* pointer in static data; the string literal is in read-only static data */
int add(int a, int b) { /* the code is in the code area */
int sum = a + b; /* a, b and sum are on the stack */
counter++;
return sum;
}
int main(void) {
int x = add(2, 3); /* x is on the stack */
int *p = malloc(sizeof(int)); /* p is on the stack; the int it points to is on the heap */
*p = x;
printf("%s %d\n", msg, *p);
free(p);
return 0;
}The table shows where each name lives.
| Name | Area | Reason |
|---|---|---|
| `counter` | Static data | Global, one copy for the whole run |
| `msg` | Static data | Global pointer; the string it points to is also in static data |
| `a`, `b`, `sum` | Stack | Locals of `add`, created at each call |
| `x`, `p` | Stack | Locals of `main` |
| `*p` | Heap | Allocated with `malloc`, freed with `free` |
| Instructions of `add`, `main` | Code | Fixed at compile time |
Note that p and *p are in different areas. A pointer variable is a local on the stack, while the object it points to is on the heap.
Edge cases and common errors
- Returning the address of a local. After the function returns, its stack space is reused, so the pointer dangles. Reading through it gives undefined behavior.
- Stack overflow. Deep or unbounded recursion keeps adding activation records until the stack meets its limit.
- Memory leak. Heap memory that is never freed, and never reclaimed by a collector, stays allocated until the program ends.
- Dangling heap pointer. Using a pointer after
freeis also undefined behavior. - Static locals. A
static int ndeclared inside a function is in static data, not on the stack, so it keeps its value between calls.
int *bad(void) {
int local = 42;
return &local; /* local dies when bad returns */
}Why this matters for GATE
GATE questions in this area usually ask where a variable is stored, how many activation records exist at a given moment, or which allocation strategy a feature requires. Use these rules.
- Does the language allow recursion? Then locals need stack allocation.
- Must the data outlive the procedure that made it? Then it needs the heap.
- Is the size and lifetime fixed for the whole run? Then it can be static.
Exercise
In the C program above, in which area is each of these stored: counter, sum, *p? Also, why can sum not be statically allocated if add is made recursive?
Show answer
counter is in static data, sum is on the stack, and *p is on the heap. If add were recursive, each active call needs its own copy of sum. A single statically allocated address would be overwritten by the inner call, so locals must be allocated on the stack.
Exercise
A function g contains the declaration static int calls = 0; and increments calls on every call. In which area is calls stored, and why does it keep its value between calls?
Show answer
It is stored in static data. Its address is fixed at compile time and it exists for the whole run, so it is not destroyed when g returns, unlike a stack local.