Dynamic Memory Allocation in C with Examples
The C programming language has a feature called dynamic memory allocation that enables programmers to allocate memory as their programmes run. This indicates that the memory can be allocated by the programmer according to the needs of the software. The <stdlib.h> header file's functions are used to allocate memory dynamically. In C, there are two types of dynamic memory allocation:
- Malloc() : Memory allocation is referred to as Malloc. A large single block of memory with given size is allocated . Malloc memory is not initialised, therefore it contains garbage value.
pointer_name = (cast-type*) malloc(size);
- Calloc() : Contiguous memory allocation is referred to as Calloc.The calloc function allows us to allocate memory in multiple blocks of the same size. It is used to initialise the memory to zero and allocate a block of memory on the heap.
pointer_name = (cast-type*) calloc(size);
The following C sample programme uses malloc and calloc functions to show how to allocate dynamic memory:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr1, *ptr2;
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
// dynamic memory allocation using malloc
ptr1 = (int*)malloc(n * sizeof(int));
// dynamic memory allocation using calloc
ptr2 = (int*)calloc(n, sizeof(int));
// Check if memory allocation is successful
if (ptr1 == NULL || ptr2 == NULL)
{
printf("Memory allocation failed.");
exit(1);
}
// Store values using malloc
printf("Enter values using malloc:");
for(i = 0; i < n; i++) {
scanf("%d", &ptr1[i]);
}
// Store values using calloc
printf("Enter values using calloc:");
for(i = 0; i < n; i++) {
scanf("%d", &ptr2[i]);
}
// Print values using malloc
printf("Values stored using malloc are: ");
for(i = 0; i < n; i++)
{
printf("%d ", ptr1[i]);
}
// Print values using calloc
printf("Values stored using calloc are: ");
for(i = 0; i < n; i++)
{
printf("%d ", ptr2[i]);
}
// Deallocate memory
free(ptr1);
free(ptr2);
return 0;
}