Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Dynamic memory allocation in C

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 308
    Comment on it

    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 :

    1. malloc : allocates the specified number of bytes
    2. realloc : increases or decreases the size of the specified block of memory. Reallocates it if needed
    3. calloc : allocates the specified number of bytes and initializes them to zero
    4. 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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: