Dynamic Memory Allocation is the process of allocating memory at runtime using pointers. Unlike static memory allocation, dynamic memory allows the program to request memory from the heap during execution.
malloc() β Allocates a single block of memorycalloc() β Allocates and initializes multiple blocksrealloc() β Reallocates memory to change its sizefree() β Frees dynamically allocated memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
// Allocate memory using malloc
ptr = (int*) malloc(n * sizeof(int));
// Check if memory is allocated
if (ptr == NULL) {
printf("Memory allocation failed!");
return 1;
}
// Use the memory
for (int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
printf("Elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
// Free the memory
free(ptr);
return 0;
}
malloc(n * sizeof(int)) β allocates memory for n integers.ptr[i] β accesses the dynamically allocated array.free(ptr) β releases the memory to prevent memory leaks.malloc() or calloc() is NULL.