A running C program has several memory regions: the text segment (machine code), the data segment (initialized globals), the BSS segment (zero-initialized globals), the heap (dynamic allocations, grows upward), and the stack (local variables and call frames, grows downward). String literals usually live in read-only data.
Keep these facts handy while you work with Memory Layout of a C Program in C.
Topic
Detail
Text
Code and read-only constants
Data / BSS
Globals and statics (initialized / zeroed)
Heap
Dynamic allocations, freed manually
Stack
Locals, parameters, return addresses
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Stack and Heap Memory.
Example 1 — Where each variable lives
Comments mark the region; the output shows that BSS starts zeroed.
C
#include <stdio.h>
#include <stdlib.h>
int initialized = 5; /* data segment */
int zeroed; /* BSS: starts at 0 */
static const char *msg = "hi"; /* pointer in data, text in read-only memory */
int main(void) {
int local = 1; /* stack */
int *heap = malloc(sizeof *heap); /* heap */
if (!heap) return 1;
*heap = 99;
printf("initialized=%d zeroed=%d\n", initialized, zeroed);
printf("local=%d heap=%d msg=%s\n", local, *heap, msg);
free(heap);
return 0;
}
Output
initialized=5 zeroed=0
local=1 heap=99 msg=hi
How It Works
Globals with an initializer go to the data segment; uninitialized ones go to BSS and start at zero.
local lives in main's stack frame and vanishes when main returns.
*heap stays valid until free.
Edge Cases & Pitfalls
Check these before relying on Memory Layout of a C Program in real programs.
assume
Assuming exact addresses
The standard does not define stack direction or layout. These pictures describe typical systems only.
stack
Huge stack arrays
The stack is small (often 1 to 8 MB). Put large buffers on the heap or make them static.
Remember
Key Takeaways
Static: data and BSS last the whole program.
Stack: automatic, small, fast.
Heap: manual, large, flexible.
One line: A running C program has several memory regions: the text segment (machine code), the data segment (initialized globals), the BSS segment (zero-initialized globals), the heap (dynamic allocations, grows upward), and the stack (local variables and call frames, grows downward).
Frequently Asked Questions
BSS holds global and static variables that have no explicit initializer. The loader zero-fills it, so it takes no space in the executable file.
Usually in a read-only part of the program image, which is why modifying a literal is undefined behavior.
Continue with "C Stack and Heap Memory" next. Compare automatic stack storage with manually managed heap storage. The C Dynamic Memory Allocation hub lists every topic in order.