C Memory Layout — Stack, Heap, Data, Text
601 words
3 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# C Memory Layout — Stack, Heap, Data, Text ## 🎯 Learning Objectives - Draw the memory layout of a C program - Differentiate between stack and heap allocation - Explain the lifetime of static, automatic, and allocated variables - Recognize common memory errors * * * ## 1. Process Memory Layout *(Diagram)* ### 1.1 S...

C Memory Layout — Stack, Heap, Data, Text
🎯 Learning Objectives
- Draw the memory layout of a C program
- Differentiate between stack and heap allocation
- Explain the lifetime of static, automatic, and allocated variables
- Recognize common memory errors
1. Process Memory Layout
(Diagram)
1.1 Segment Descriptions
| Segment | Contents | Lifetime | Growth | Example |
|---|---|---|---|---|
| Text | Program code (instructions) | Entire program | Fixed | int main() { ... } |
| Data | Initialized globals/statics | Entire program | Fixed | int x = 10; |
| BSS | Uninitialized globals/statics | Entire program | Fixed | int y; |
| Heap | Dynamically allocated memory | malloc→free | Upward | malloc(100) |
| Stack | Local variables, function frames | Function call→return | Downward | int z; |
1.2 Example: Where Variables Live
c#include <stdio.h> #include <stdlib.h> int global_init = 42; // Data segment int global_uninit; // BSS segment void func() { int local = 10; // Stack static int static_var = 5; // Data segment int *heap_var = malloc(sizeof(int)); // Heap (pointer on stack) *heap_var = 100; printf("Code (text): %p\n", (void*)func); printf("Global init: %p\n", (void*)&global_init); printf("Global uninit: %p\n", (void*)&global_uninit); printf("Static: %p\n", (void*)&static_var); printf("Heap: %p\n", (void*)heap_var); printf("Local (stack): %p\n", (void*)&local); free(heap_var); }
Output (addresses will vary):
pseudoCode (text): 0x400500 Global init: 0x601040 Global uninit: 0x601060 Static: 0x601044 Heap: 0x1a26010 Local (stack): 0x7ffd5a1e4b2c
2. Stack vs Heap Comparison
| Aspect | Stack | Heap |
|---|---|---|
| Speed | Fast (allocation = SP adjust) | Slow (malloc must find free block) |
| Size | Small (typically 1-8 MB) | Large (limited by RAM) |
| Lifetime | Automatic (function scope) | Manual (malloc → free) |
| Memory management | Automatic | Manual (or GC) |
| Fragmentation | None | External fragmentation |
| Thread safety | Per-thread (each thread has own stack) | Shared (needs synchronization) |
3. Common Memory Errors
3.1 Stack Overflow
cvoid infinite_recursion() { int arr[1000]; // 4KB each call infinite_recursion(); // Eventually overflows stack }
3.2 Buffer Overflow
cchar buffer[10]; strcpy(buffer, "This string is way too long!"); // Overwrites adjacent memory
3.3 Use-After-Free
cint *p = malloc(sizeof(int)); free(p); *p = 42; // Undefined behavior! p is dangling
3.4 Memory Leak
cvoid leak() { int *p = malloc(1000000); // Allocated // Never freed! }
4. 📝 Practice Questions
Q1: Where are the following variables stored?int a = 5; static int b; int c; void f() { int d; static int e; }Answer: a: Data segment (initialized global). b: BSS (uninitialized static). c: BSS (uninitialized global). d: Stack (local in function). e: Data segment (initialized to 0 static local). Q2: Why is stack allocation faster than heap allocation?Answer: Stack allocation is just adjusting the stack pointer (one instruction). Heap allocation must search for a suitable free block, possibly splitting or coalescing blocks, and may involve system calls (brk/sbrk) to extend the heap. Q3: What happens when the stack grows into the heap?Answer: This causes a stack overflow (SEGFAULT). The OS detects the invalid memory access and terminates the program. In modern OS with virtual memory, the stack and heap are far apart with guard pages. Q4: How does a memory leak affect a long-running program?Answer: Each leak reduces available heap memory. Over time, the program's memory usage grows (memory bloat), eventually exhausting system memory or triggering OOM (Out-of-Memory) killer. This is especially critical in servers and embedded systems. Q5: What is the difference between BSS and Data segments?Answer: Both store global/static data. BSS stores uninitialized variables (set to 0 at runtime). Data stores initialized variables (values loaded from the executable file). BSS saves disk space because it doesn't need to store zeros in the executable.
5. 🔗 Cross-References
- Week 3 - Pointers: Pointer arithmetic and memory access
- Week 5 - Dynamic Memory: malloc/calloc/free details
- BSCS4022 (OS): Process memory management, virtual memory Join Discord NextControl Flow & Arrays