What is dynamic memory allocation?
In C, dynamic memory allocation is the process of allocating memory during program execution (runtime), instead of compile time.
It allows programs to request memory as needed and release it when it is no longer required.
Instead of deciding memory size beforehand, you ask for it while the program is running.
Why do we need it?
- 📦 Handle unknown data size at runtime
- ⚡ Efficient memory usage
- 🔁 Flexible data structures (linked lists, trees)
- 📈 Scalable applications
Memory types in C
- Stack memory — static allocation
- Heap memory — dynamic allocation
malloc()
Allocates a single block of memory.
int *ptr = (int*) malloc(5 * sizeof(int));
calloc()
Allocates multiple blocks and initializes them to zero.
int *ptr = (int*) calloc(5, sizeof(int));
realloc()
Resizes previously allocated memory.
ptr = (int*) realloc(ptr, 10 * sizeof(int));
free()
Releases allocated memory back to the system.
free(ptr);
Example program
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *arr = (int*) malloc(n * sizeof(int));
for(int i = 0; i < n; i++) {
arr[i] = i + 1;
}
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}
Advantages
- Efficient memory usage
- Flexible program design
- Supports complex data structures
Disadvantages
- Memory leaks if not freed
- Slower than stack memory
- Manual management required
Always use free() after dynamic allocation to avoid memory leaks.
Summary
Dynamic memory allocation in C allows memory to be allocated and managed at runtime using heap memory. It is essential for flexible and efficient programs.