What functions are used for dynamic memory allocation in C language?

  1. malloc()
    • The malloc() function is used to allocate the memory during the execution of the program.
    • It does not initialize the memory but carries the garbage value.
    • It returns a null pointer if it could not be able to allocate the requested space.

    Syntax

    1. ptr = (cast-type*) malloc(byte-size) // allocating the memory using malloc() function.  

  2. calloc()
    • The calloc() is same as malloc() function, but the difference only is that it initializes the memory with zero value.

    Syntax

    1. ptr = (cast-type*)calloc(n, element-size);// allocating the memory using calloc() function.  

  3. realloc()
    • The realloc() function is used to reallocate the memory to the new size.
    • If sufficient space is not available in the memory, then the new block is allocated to accommodate the existing data.

    Syntax

    1. ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.  

    In the above syntax, ptr is allocated to a new size.

  4. free():The free() function releases the memory allocated by either calloc() or malloc() function.
  5. Syntax

    1. free(ptr); // memory is released using free() function.  

    The above syntax releases the memory from a pointer variable ptr.