Dynamic memory allocation is a manual memory management for the dynamic memory with use of some group of functions in like  malloc, realloc, calloc and free. The process of allocating memory during the execution of a C program is called a Dynamic memory allocation.
The Function that performs the same in C with their description :
- malloc : allocates the specified number of bytes
- realloc : increases or decreases the size of the specified block of memory. Reallocates it if needed
- calloc : allocates the specified number of bytes and initializes them to zero
- free : releases the specified block of memory back to the system
Example to show malloc() function in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
     char *mem_allocate;
     mem_allocate = malloc( 20 * sizeof(char) );
     if( mem_allocate == NULL )
     {
        printf("Couldn't able to allocate requested memory\n");
     }
     else
     {
        strcpy( mem_allocate,"xyz");
     }
     printf("Dynamically allocated memory content : " \
            "%s\n", mem_allocate );
     free(mem_allocate);
}
Output:
Dynamically allocated memory content : xyz
Example to show calloc() function in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
     char *mem_allocate;
     mem_allocate = calloc( 20, sizeof(char) );
     if( mem_allocate== NULL )
     {
        printf("Couldn't able to allocate requested memory\n");
     }
     else
     {
         strcpy( mem_allocate,"xyz");
     }
         printf("Dynamically allocated memory content   : " \
                "%s\n", mem_allocate );
         free(mem_allocate);
}
Output:
Dynamically allocated memory content : xyz
The main differences of malloc and calloc is that malloc() does not initialize the memory allocated, while calloc() initializes all the bytes of the allocated memory block to zero.
                       
                    
0 Comment(s)