Dynamic Memory Allocation (DMA) is the process of allocating memory during the execution of a program (at runtime) instead of at compile time. It allows programs to request memory as needed, making memory usage more efficient.
Why Dynamic Memory Allocation is Needed
- Memory requirements may not be known before program execution.
- Prevents memory wastage by allocating only the required amount.
- Enables creation of dynamic data structures like linked lists, trees, and graphs.
Dynamic Memory Allocation Functions in C
The <stdlib.h> header file provides four functions:
malloc()(Memory Allocation)- Allocates a block of memory of the specified size.
- Memory contents are uninitialized (contain garbage values).
- Syntax:
int *ptr = (int *)malloc(5 * sizeof(int));
calloc()(Contiguous Allocation)- Allocates memory for multiple elements.
- Initializes all allocated memory to zero.
- Syntax:
int *ptr = (int *)calloc(5, sizeof(int));
realloc()(Reallocation)- Changes the size of previously allocated memory.
- Syntax:
ptr = (int *)realloc(ptr, 10 * sizeof(int));
free()- Releases dynamically allocated memory back to the system.
- Syntax:
free(ptr);
Example Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i;
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 elements:\n");
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Elements are:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
free(arr); // Release memory
return 0;
}
Advantages
- Efficient memory utilization.
- Memory can be allocated as needed.
- Supports dynamic data structures.
- Can resize memory using
realloc().
Disadvantages
- Slightly slower than static allocation.
- Memory leaks can occur if
free()is not used. - Improper use may cause dangling pointers or fragmentation.
In summary: Dynamic memory allocation allows a program to allocate, resize, and free memory at runtime using malloc(), calloc(), realloc(), and free()
Category: MCA
