Loading lessons...
Dynamic Memory Management
Dynamic Memory Management
C programs can ask for memory while running, not just at compile time. That's dynamic memory.
Why dynamic memory?
- You don't always know at compile time how much you need.
- Arrays have fixed sizes; dynamic memory can grow on demand.
- Big structures need room beyond the stack.
The players
The functions live in <stdlib.h>:
malloc(size) // allocate
calloc(n, size) // allocate + zero
realloc(ptr, s) // resize
free(ptr) // release
The golden rule
Everything you allocate, you must eventually free. C does not clean up for you.
Include
#include <stdlib.h>
TL;DR
- Dynamic memory is allocated while running.
- malloc, calloc, realloc allocate; free releases.
- The lifecycle is manual in C - do not forget free.
- Allocation functions come from <stdlib.h>.