IDRASAcademic OS
Unit 1: C Memory Architecture, Dynamic Allocation & Pointer Mechanics 35 mins study timeINTERMEDIATE

C Dynamic Memory Lifecycle: malloc, calloc, realloc, free & Valgrind Diagnostics

In-depth breakdown of the OS heap allocator, brk/sbrk system calls, memory fragmentation, dangling pointers, memory leaks, and memory sanitizer tooling.

Verified: Faculty Peer Review Board

Learning Objectives

  • •Map global, static, local, and heap variables into the 5 Linux process memory segments.
  • •Differentiate malloc, calloc, realloc, and free in terms of initialization and performance.
  • •Calculate exact struct memory padding and alignment layouts manually.
  • •Diagnose memory leaks, heap buffer overflows, and use-after-free bugs with Valgrind / AddressSanitizer.

Essential Prerequisites

  • •Basic C syntax and pointer dereferencing
  • •sizeof operator
Layer 1: Intuition & Why It Matters

The Core Mental Model

“The stack is like a stack of plates in a cafeteria: you take one off, eat, and put it back automatically. The heap is like renting a storage unit downtown: you must explicitly sign a lease (malloc), put furniture inside, and remember to cancel the lease (free). If you throw away the key without canceling, you pay rent forever (Memory Leak).”

Why This Exists

Linux kernels, high-performance database engines (PostgreSQL, SQLite), web servers (Nginx), and game engines are written in C. In C, you are directly manipulating physical memory bytes. A single uninitialized pointer or buffer overflow can crash entire operating systems or open severe security vulnerabilities.

Beginner Foundation

In C, when you declare an array like `int arr[10]`, it dies when the function ends. But if you want to download a file of unknown size and keep it in RAM, you must ask the operating system for dynamic memory using `malloc()`.

Micro Concepts Decomposition

MICRO CONCEPT 1Canonical Object

The Five Process Memory Segments

A running C binary in Linux maps into: 1) Text Segment (read-only machine code instructions), 2) Initialized Data (.data, global/static variables with non-zero initial values), 3) BSS (.bss, uninitialized globals/statics zeroed by OS kernel), 4) Heap (grows upwards via malloc/brk), 5) Stack (grows downwards with stack frames and local variables).

Key Takeaway: Stack is automatic and fast; Heap is manual, flexible, and persistent until explicitly freed.
MICRO CONCEPT 2Canonical Object

malloc vs calloc vs realloc Internal Mechanics

malloc(size) allocates uninitialized bytes on the heap. calloc(num, size) allocates and zeroes all bytes using kernel zero-pages. realloc(ptr, new_size) attempts in-place growth or allocates a new block, copies existing payload, and frees the old pointer.

Key Takeaway: Always check if pointer returned by malloc/calloc/realloc is NULL (Out of Memory).
MICRO CONCEPT 3Canonical Object

Dangling Pointers, Double Free & Memory Leaks

A Memory Leak occurs when heap memory is never freed before losing its pointer reference. A Dangling Pointer occurs when a pointer is accessed after its target memory was already freed. Double Free occurs when free(ptr) is called twice on the same address.

Key Takeaway: Mitigate dangling pointers by immediately assigning `ptr = NULL` immediately following `free(ptr)`.
MICRO CONCEPT 4Canonical Object

Struct Memory Padding & Natural Alignment Boundaries

CPUs access memory much faster when data addresses are multiples of data size (e.g. 4-byte integers on 4-byte boundaries, 8-byte doubles on 8-byte boundaries). Compilers automatically insert padding bytes between struct fields. Total struct size is padded to a multiple of its largest member.

Key Takeaway: Reorder struct members from largest to smallest to minimize memory padding waste.
Layer 3 & 4: Formal Specification & Mechanism

Hardware State Machine Architecture

glibc ptmalloc allocator architecture: Uses chunk headers containing previous chunk size, current chunk size, and flag bits (A, M, P). Small allocations (<128 KB) expand the data segment via `brk()`. Large allocations (>=128 KB) allocate distinct anonymous virtual memory pages via `mmap()` directly from the OS kernel.
Step-by-Step Struct Padding Calculation: ```c struct BadLayout { char a; // 1 byte (offset 0) // 3 padding bytes inserted so b is aligned to 4-byte boundary int b; // 4 bytes (offset 4) char c; // 1 byte (offset 8) // 7 padding bytes inserted so d is aligned to 8-byte boundary double d; // 8 bytes (offset 16) }; // Total size = 24 bytes (10 bytes of data + 14 bytes wasted padding!) struct OptimizedLayout { double d; // 8 bytes (offset 0) int b; // 4 bytes (offset 8) char a; // 1 byte (offset 12) char c; // 1 byte (offset 13) // 2 tail padding bytes to make total multiple of 8 }; // Total size = 16 bytes (Saved 33% memory!) ```
Layer 7: Interactive Laboratory

Interactive Simulator

COA • SIMULATIONC Pointers, Memory Addresses & Dereferencing Simulator
Launch Fullscreen Lab
COA • CPU ARCHITECTUREOperand Fetch & Memory Dereference

Addressing Modes & Effective Address (EA) Visualizer

1. Instruction Opcode
LOAD R1, 8(R2)
Mode: INDEXED Addressing Mode
Base register plus index/offset value
2. Address Resolution Unit
DERIVATION FORMULA:
EA = [R2] + Displacement/Offset = 0x1004 + 0x0008 = 0x100C
Resolved EA: 0x100C
Memory Bus Accesses: 1 cycle(s)
3. Final Operand Fetched
0x7777 (MEM[0x100C])
Ideal for array and struct indexing (Array base address + index * element size).
CPU Internal Register FileWord-size: 16-bit
R10x0000General Purpose
R20x1004General Purpose
PC0x0200Program Counter
XR0x0008Index Register
RAM Physical Address SpaceWord Addressable
5200x9999Memory Word
40960x0042Memory Word
41000x2000Memory Word
41080x7777Memory Word
81920x5555Memory Word
Layer 5: Step-by-Step Worked Numerical Example

End-to-End Execution Trace

Problem: Trace the behavior of realloc failure: ```c int *ptr = malloc(100 * sizeof(int)); ptr = realloc(ptr, 1000000 * sizeof(int)); // BUG! ``` Why is this a critical bug? If realloc fails due to out-of-memory, it returns NULL. Overwriting `ptr` with NULL destroys the original memory address, permanently leaking the original 100 integers! Correct idiom: store in temporary pointer `int *tmp = realloc(ptr, new_sz); if (tmp) ptr = tmp;`.
Layer 6: Active Runtime CodeLab

Step-by-Step Code Execution (C)

Font
main.cGlacier Light
Ln 1 • GCC 13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
1529 chars • 47 lines • Ln 1UTF-8 • 4 Spaces
Interactive Terminal Shell

Sandbox Terminal Ready

Click Run Code or press Ctrl+Enter to compile and execute.

Common Student Pitfalls & Mistakes

Where Students Lose Marks

❌ Mistake: Calling free() on a pointer that was not returned by malloc/calloc/realloc (e.g. stack address or middle of array).
✓ Correct Understanding: free() requires the exact base address returned by the heap allocator because chunk headers precede that address. Freeing invalid addresses causes immediate segmentation fault.
Layer 8: Practice & Knowledge Verification

Active Assessment Quiz

No Practice Questions Configured

Questions for this topic are currently undergoing faculty review.

Academic Evaluation Preparation

Viva Examination & University Scoring Strategy

Standard Viva Examination Questions

Q1: What is the difference between malloc() and calloc()?
Answer: malloc() allocates raw uninitialized memory leaving whatever garbage bits were previously in RAM. calloc() initializes all allocated bytes to zero. calloc() also accepts two arguments (number of elements and size per element) and checks for integer multiplication overflow.

How to Write High-Scoring University Exam Answers

Describe the five segments of C process memory with a visual memory map. Explain malloc, calloc, realloc, and free with syntax and error handling. Explain struct padding with an example comparing bad and optimized field orders.