Jan 22, 2026
## Chapter 12: Dynamic Memory Allocation
The arrays we have created so far had a fixed size at compile time. In real programs, memory size is often known only at runtime. This is where dynamic memory allocation comes in.
What is Dynamic Memory Allocation? (Simple Language)
Allocating memory while the program is running (runtime) and releasing it when the work is done.
* Need memory → allocate
* Work finished → free
Memory Allocation Functions (stdlib.h):
* `malloc()`
* `calloc()`
* `realloc()`
* `free()`
Practical Example: Creating a Runtime Array
```c
#include
#include
int main() {
int *numbers;
int count;
printf("How many elements do you need? ");
scanf("%d", &count);
// Allocate memory at runtime
numbers = (int *)malloc(count * sizeof(int));
// Check allocation
if (numbers == NULL) {
printf("Memory allocation failed!n");
return 1;
}
// Use the allocated memory
for(int i = 0; i < count; i++) {
numbers[i] = (i + 1) * 5;
}
printf("Stored values:n");
for(int i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
printf("n");
// Release memory
free(numbers);
return 0;
}
```
1. Why a pointer?: Dynamic memory is created in the heap; its address is stored in a pointer.
2. `malloc()`: allocates memory and returns the starting address.
3. Allocation check: `if (numbers == NULL)` is mandatory.
4. `free()`: releasing memory is necessary to prevent memory leaks.
Memory Functions (Short Overview)
| Function | Purpose |
| :--- | :--- |
| `malloc(size)` | Allocates memory |
| `calloc(n, size)` | Allocates memory + initializes to zero |
| `realloc()` | Resizes existing memory |
| `free(ptr)` | Returns memory to the system |
`malloc()` vs `calloc()`
| `malloc()` | `calloc()` |
| :--- | :--- |
| Contains garbage values | Memory initialized to zero |
| Faster | Slightly slower |
| Single block | Multiple blocks |
---