Dynamic Memory Allocation (uwu)
What is Dynamic Memory Allocation?
Dynamic memory allocation lets you allocate memory at runtime (while the program is running), instead of at compile time (like with arrays).
This is useful when you don’t know in advance how much memory you’ll need — like when you're getting user input or working with variable-sized data.
The Key Functions (from <stdlib.h>)
Function | Purpose |
|---|---|
| Allocates a block of memory |
| Allocates and initializes memory to zero |
| Resizes previously allocated memory |
| Frees memory that was allocated dynamically |
malloc()int *arr = (int*) malloc(5 * sizeof(int));Allocates memory for 5 integers.
sizeof(int)is the size (in bytes) of an integer.Returns a pointer to the first element of the block.
The memory contains garbage values, so initialize it yourself.
calloc()int *arr = (int*) calloc(5, sizeof(int));Sets all values to zero.
Allocates space for 5 integers.
Safer than
malloc()if you need zero-initialization.
realloc()arr = (int*) realloc(arr, 10 * sizeof(int));Changes the size of the memory block (e.g., from 5 to 10 ints).
Useful for growing arrays dynamically.
free()free(arr);Releases the memory you've allocated with
malloc,calloc, orrealloc.Always free memory when you’re done to avoid memory leaks.
Key Notes
Always check if memory allocation succeeded:
if (arr == NULL) { printf("Memory allocation failed!\n"); }Don’t forget to
free()what youmalloc()— every allocation should have a matching free.
Example Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr = (int) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter %d numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("You entered:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
free(arr); // Clean up memory
return 0;
}