Why Dynamic Allocation?
Local arrays have fixed sizes determined at compile time. Dynamic allocation lets you request memory at runtime — essential for data structures, user-driven data, and programs that don't know their data size in advance.
The Big Four: malloc, calloc, realloc, free
malloc — Allocate Memory
c
calloc — Allocate and Zero-Initialize
c
realloc — Resize Allocated Memory
c
Warning:reallocmay move the block to a new address. Always reassign:arr = realloc(arr, new_size). But never doptr = realloc(ptr, size)without error checking — if it fails, you lose the original pointer!
c
free — Release Memory
c
Critical Rules:
- Always
free()what youmalloc()- Never
free()the same pointer twice (double-free)- Never use memory after
free()(use-after-free)- Set pointer to
NULLafter freeing
Practical Example: Dynamic Array
c
Summary
| Function | Purpose | Initialized? |
|---|---|---|
malloc(size) | Allocate bytes | ❌ Garbage |
calloc(n, size) | Allocate and zero | ✅ Zeroed |
realloc(ptr, size) | Resize allocation | Preserved |
free(ptr) | Release memory | — |