Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 135 ยท Memory Management

Memory Layout of a C Program

See how a running C program is laid out in memory - the text, data and bss segments, the heap and the stack - print real addresses, and learn why the stack has limits.

When your program runs, the operating system gives it a private range of addresses called its address space. Your code, your global variables, your heap blocks and your function calls all live somewhere inside it, in distinct regions with different rules. Knowing those regions turns many confusing C behaviors into obvious ones: why a local array vanishes when a function returns, why a static variable remembers its value, why modifying a string literal can crash, and why deep recursion ends in a stack overflow.

This lesson describes the classic layout used by Linux, macOS, Windows and most other systems, then lets you print real addresses to see it for yourself. The C standard doesn't actually mention segments or stacks. It talks about storage durations (static, automatic, allocated and thread). The segments below are how real compilers and operating systems implement those durations.

The big picture

A typical process looks like this, with low addresses at the bottom:

TEXT
 high addresses
 +---------------------------+
 | command-line args, env    |
 +---------------------------+
 | stack                     |  grows down: one frame per active call
 |            |              |
 |            v              |
 |                           |
 |   (unused address space)  |
 |                           |
 |            ^              |
 |            |              |
 | heap                      |  grows up: malloc / calloc / realloc
 +---------------------------+
 | bss                       |  globals and statics that start at zero
 +---------------------------+
 | data                      |  globals and statics with initial values
 +---------------------------+
 | rodata                    |  string literals, const globals
 +---------------------------+
 | text                      |  machine code of your functions
 +---------------------------+
 low addresses

Shared libraries (like the C library itself) and memory-mapped files are placed in the large gap in the middle. Large malloc requests are often served from there too, through mmap, rather than from the classic heap area.

Region What lives there Storage duration Writable?
text Compiled functions static No
rodata String literals, many const globals static No
data Initialized globals and static variables static Yes
bss Zero-initialized globals and static variables static Yes
heap Blocks from malloc and friends allocated Yes
stack Local variables, parameters, return addresses automatic Yes

Seeing the regions with real addresses

Let's print one address from each region. %p expects a void *, so each pointer is converted explicitly. Function pointers can't portably be converted to void *, so the example goes through uintptr_t from <stdint.h> and prints the number in hex with PRIxPTR from <inttypes.h>.

C One address from every region

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Your exact numbers will differ from run to run. Modern systems use address space layout randomization (ASLR): every time the program starts, the operating system shifts the regions by random amounts, so attackers can't guess where things are. The pattern, though, is stable on Linux x86-64, which our editor uses: text, rodata, data and bss come first at low addresses close to each other, the heap starts a bit above them, and the stack sits far away at a very high address (it typically starts with 0x7ff...).

Note: comparing pointers with < or > is only defined when both point into the same array or object. To compare addresses of unrelated objects, as a debugging curiosity, convert them to uintptr_t first. Even then the result is implementation-defined, which is fine for exploring but not for program logic.

Text and rodata: code and constants

The text segment holds the machine code of your functions. It's mapped read-only and executable, so a stray pointer can't accidentally rewrite your program. Right next to it, rodata ("read-only data") holds string literals and usually const globals.

This is why the C standard says modifying a string literal is undefined behavior, and why on most systems it crashes with a segmentation fault:

C
char *word = "cat";      /* points into rodata */
word[0] = 'b';           /* undefined behavior: usually crashes */

char safe[] = "cat";     /* an array COPY of the literal, on the stack */
safe[0] = 'b';           /* fine: safe now holds "bat" */

Declaring the pointer as const char *word makes the compiler reject the write, which is why that's the recommended type for literals (see Strings). Identical literals may also be merged into one copy, so two pointers to "cat" can compare equal.

Data and bss: variables that live forever

Variables with static storage duration exist for the entire run: globals, and locals marked static (covered in Scope and Storage Classes). They go into one of two segments:

  • data holds the ones with a non-zero initial value. Those values must be stored in the executable file, so a big initialized array makes your program file bigger.
  • bss holds the ones that start at zero, either explicitly (= 0) or because statics without an initializer are zero-initialized. The file only records how big bss is; the loader fills it with zeros at start-up. That's why a 4 MB zeroed global table costs nothing on disk.
C Static storage lives for the whole program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows tickets 101, 102 and 103, calls so far: 3, and a 4,000,000-byte table full of 0.0. ticket keeps its value between calls because it lives in the data segment, not in next_ticket's stack frame. Its initializer runs exactly once, conceptually before main starts, not on every call.

Static storage is convenient, but it's shared state: every caller sees the same variable, which makes functions harder to test and unsafe to call from several threads at once. Prefer locals and parameters, and reach for statics deliberately.

The heap

The heap is the region managed by malloc, calloc, realloc and free, which you met in Dynamic Memory. The C library asks the operating system for big chunks of memory and carves them into the blocks you request. Each block carries a little hidden bookkeeping (usually 8 or 16 bytes just before the address you get), and blocks are aligned so that any type fits; on 64-bit Linux, malloc results are multiples of 16.

That hidden bookkeeping is exactly what overruns and double frees corrupt, which is why those bugs often crash later, inside a completely unrelated malloc or free call (see Memory Errors).

The stack and stack frames

Every function call gets a stack frame: a chunk of the stack holding the function's local variables, saved registers and the address to return to. Calling a function pushes a frame; returning pops it. Because the frame is simply abandoned on return, local variables vanish, and the same memory gets reused by the next call. That's the whole reason a pointer to a local becomes dangling after its function returns.

You can watch frames stack up by printing the address of a local at each level of recursion:

C Each call gets its own frame

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

On x86-64 the addresses get smaller at each level: the stack grows downward, toward the heap. Each level sits the same distance below the previous one, and that distance is the size of one descend frame: 48 bytes with our compiler settings. The exact frame size depends on the compiler, the target and the optimization level, so expect a different number on your machine. The distance at depth 0 isn't zero because start lives in main's frame, one level up.

Stack size limits and stack overflow

The stack is small. On Linux the main thread's stack defaults to 8 MB, on macOS 8 MB, and on Windows just 1 MB; extra threads often get even less. Two things exhaust it:

  • Deep or runaway recursion. A recursion with no reachable base case adds frames until the stack runs out.
  • Large local arrays. double samples[2000000]; inside a function needs 16 MB of stack in one go.

Running out is called a stack overflow. The memory just beyond the stack is protected, so the program usually dies with a segmentation fault, with no friendly message. You can check and change the limit for your shell on Linux or macOS:

Terminal
ulimit -s          # prints 8192 (kilobytes) on a typical Linux system
ulimit -s 65536    # raise it to 64 MB for programs started from this shell

Raising the limit is a workaround. The real fix is to put big data on the heap, or in static storage if one copy is enough, and to turn deep recursion into a loop:

C Big buffers belong on the heap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The values cycle through 0, 1, 4, ... 81, so the average is 28.50. The heap version works no matter how small the stack is, and the NULL check gives you a clean error path instead of a crash.

Tip: a good rule of thumb is to keep individual stack objects under a few kilobytes. Anything bigger, or anything whose size comes from input, goes on the heap.

How this connects to storage durations

To tie it back to the C standard's terms:

Storage duration Declared how Lifetime Usual region
static Globals, static locals Whole program data or bss
automatic Ordinary locals and parameters Until the block ends stack (or just registers)
allocated malloc, calloc, realloc Until free heap
thread (C11) thread_local / _Thread_local Until the thread ends per-thread storage

One subtlety: the optimizer is free to keep automatic variables purely in CPU registers, with no stack address at all, unless you take their address (as the examples do with &). The layout model describes where things can live, not a promise for every variable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. static int counter = 5; inside a function. Where does counter usually live?

    Static locals have static storage duration. A non-zero initializer puts them in the data segment; they keep their value between calls.
  2. 2. Why does a large zero-initialized global array not make the executable file bigger?

    bss content is all zeros by definition, so only its size is stored in the file.
  3. 3. A recursive function prints the address of a local at each depth on x86-64 Linux. What do you expect to see?

    Each active call has its own frame, and the stack grows downward on x86-64, so deeper frames have smaller addresses.
  4. 4. Why does running the same program twice usually print different addresses?

    ASLR moves the stack, heap, libraries and often the executable to random positions each run, as a security measure.
  5. 5. A function declares char buffer[32 * 1024 * 1024]; and the program crashes as soon as the function is called. What is the best fix?

    32 MB is far beyond typical stack limits (1โ€“8 MB). Heap memory can be that large, and malloc reports failure with NULL instead of crashing.

Summary

  • A process's memory is divided into regions: text (code), rodata (literals and constants), data (initialized statics), bss (zeroed statics), the heap and the stack.
  • Text and rodata are read-only, which is why modifying a string literal usually crashes.
  • Globals and static locals live for the whole program; bss items cost no space in the executable.
  • The heap holds malloc blocks until you free them; allocator bookkeeping sits next to your blocks, which is why overruns corrupt the heap.
  • Each call gets a stack frame that disappears on return. On x86-64 the stack grows downward.
  • The stack is small (often 1โ€“8 MB): keep big or input-sized data on the heap and avoid unbounded recursion.
  • ASLR randomizes the addresses each run; the C standard itself only defines storage durations, not segments.

Next: Building a Dynamic Array, where you'll put the heap to work in a growable array, first of ints and then of any type.