Introduction to dynamic memory allocation

A technique used in computer programming called dynamic memory allocation allocates memory while the programme is running rather than at compile time. In other words, the amount of memory needed by a programme might not be known in advance, and it is not practicable to set aside memory at the time of programme compilation for every potential need. In these circumstances, memory is allocated dynamically during programme execution as needed.

In C language, dynamic memory allocation is achieved using four library functions defined in <stdlib.h> header file: malloc(), calloc(), realloc() and free().

  • The malloc() function is used to allocate memory dynamically. It takes the number of bytes to allocate as an argument and returns a pointer to the first byte of the allocated memory block.

  • The calloc() function is used to allocate and initialize memory for an array of elements. It takes two arguments: the number of elements to allocate memory for and the size of each element, and returns a pointer to the first byte of the allocated memory block.

  • The realloc() function is used to resize a previously allocated block of memory. It takes two arguments: a pointer to the previously allocated memory block and the new size to allocate, and returns a pointer to the first byte of the resized memory block.

  • The free() function is used to deallocate memory that was previously allocated using malloc(), calloc(), or realloc().