Why do we need dynamic memory allocation techniques? Explain the functions available for allocating memory dynamically.
DYNAMIC MEMORY ALLOCATION----
- It refers to performing manual management for dynamic memory allocation using standard library functions such as malloc, realoc, calloc and free.
- The size of array initially declared can be sometimes insufficient or sometimes more than required but dynamic memory allocation allows a program to obtain more memory space, while running or to release space when not required.
FUNCTIONS OF DYNAMIC MEMORY ALLOCATION----
- There are four standard library functions under “stdlib.h” for dynamic memory allocation.
- malloc()
- calloc()
- realloc()
- free()
=> malloc() – It allocates requested size of bytes and returns a pointer first byte of allocated space.
Syntax : ptr=(data_type *)malloc(bysize);
Ex : (int*)malloc(100*sizeof(int))
=> calloc() – Allocates spaces for array elements, initializes to zero and then returns a pointer to memory.
Syntax : ptr=(data_type*)calloc(n,element_size);
Ex : ptr=(float*)calloc(25,sizeof(float))
=> realloc() – Changes the size of the previously allocated space according to the requirement.
Syntax : ptr=realloc(ptr,newsize);
=> free() – It deallocates the previously allocated space.
Syntax – free(ptr);