π C Dynamic Memory Allocation
In C, **dynamic memory allocation** allows you to allocate memory at runtime instead of compile time. It gives you control over how much memory to use and when to release it.
The standard library provides these functions from <stdlib.h>
:
malloc()
– Allocates memory blockcalloc()
– Allocates and initializes memoryrealloc()
– Resizes memory blockfree()
– Frees allocated memory
π Example: Using malloc()
Allocate memory for 5 integers dynamically using malloc()
.
#include <stdio.h> #include <stdlib.h> int main() { int *arr; int i; arr = (int*) malloc(5 * sizeof(int)); if (arr == NULL) { printf("Memory not allocated.\n"); return 1; } for (i = 0; i < 5; i++) { arr[i] = i + 1; } printf("Array elements: "); for (i = 0; i < 5; i++) { printf("%d ", arr[i]); } free(arr); return 0; }
π Example: Using calloc()
calloc()
also allocates memory, but initializes all values to 0.
#include <stdio.h> #include <stdlib.h> int main() { int *arr; int i; arr = (int*) calloc(5, sizeof(int)); if (arr == NULL) { printf("Memory not allocated.\n"); return 1; } printf("Array elements (initialized to 0): "); for (i = 0; i < 5; i++) { printf("%d ", arr[i]); } free(arr); return 0; }
π Example: Using realloc()
realloc()
is used to resize an already allocated memory block.
#include <stdio.h> #include <stdlib.h> int main() { int *arr; int i; arr = (int*) malloc(3 * sizeof(int)); if (arr == NULL) { printf("Initial allocation failed.\n"); return 1; } for (i = 0; i < 3; i++) { arr[i] = i + 1; } arr = (int*) realloc(arr, 5 * sizeof(int)); if (arr == NULL) { printf("Reallocation failed.\n"); return 1; } arr[3] = 4; arr[4] = 5; printf("Resized array: "); for (i = 0; i < 5; i++) { printf("%d ", arr[i]); } free(arr); return 0; }
β οΈ Donβt Forget to Free Memory
Whenever you use malloc()
, calloc()
, or realloc()
, remember to use free()
after you’re done. It avoids memory leaks.
π Summary
malloc(size)
β allocates raw memorycalloc(n, size)
β allocates and initializes memory to 0realloc(ptr, newSize)
β resizes memory blockfree(ptr)
β releases memory
π― Try This!
Create a program that dynamically allocates memory for a list of names using char**
. Resize the list as needed using realloc()
!