DYNAMIC MEMORY ALLOCATION
In industry memory management is very important.
There are two types of memory which is used by the program, one is Stack segment and another is Heap segment.
Stack is a special area of Computer’s memory which stores the temporary variables created by the functions. In stack variables are stored in run time. It is a temporary storage memory.
Heap is a memory used to store global variables. Heap is not managed by the CPU unit. It supports dynamic memory allocation.
Dynamic memory allocation is done with malloc(), calloc() and realloc() function.
Malloc: malloc is used to allocate a block of memory in the heap segment. Malloc allocates the memory at run time. Malloc allocates the memory in the heap segment. Dynamic memory is not cared by the CPU, so it’s required to free the memory after the use to prevent the memory leakage.
where ptr is a pointer type of variable which points the base address of the allocated memory in heap segment. After that is pointer typecast of the data.
If we allocates the ‘0’ bytes to the malloc then also it reserve some memory which is of size 32Kbytes.
The usable size of the malloc is checked by the malloc_usable_size which is 24Kbytes, and it keeps extra 8bytes with it which is chunk size.
Working of malloc function:
When we gives the size to allocate then it checks the threshold of malloc and then checks it in memory pages if available then then it allocates the memory blocks otherwise memory mapping comes into the picture(mmap).
Malloc allocates the memory in heap segment which have fixed size of 130Kbytes.
When we allocates the memory then it points the address of the page which is of 130Kbyte’s size if the requirement is more than heap then the size of heap then it calls the extra memory by mmap.
On the successful of malloc it returns the address of the allocated space. On the failure of malloc it returns the NULL .
Calloc: calloc is used to allocate dynamic memory. Dynamic memory is allocated on run time .
Calloc is similar to malloc the difference is, that the default values of the allocated blocks are zero in calloc and in malloc the default values are garbage.
Realloc:realloc is used to allocate the memory on run time whenever the extra memory required on the run time.
ptr_new=(typr-caste)realloc(ptr,new_size in bytes);
where ptr_new is the address of the new allocate space, ptr is the previous size of allocated memory.
Working of realloc function:
when realloc function is used then first it checks the available space in that page if the required space is available then it added the requested blocks of memory.
If the size is not available then an extra page comes through the memory mapping concept and reallocates the space requested and it copies the data of the current address to new allocated space and frees the previous memory.
Malloc is slightly faster than Calloc than Realoc.