Why malloc() gives more than asked memory | Dynamic Memory Allocation
Dynamic Memory Allocation is one of the memory management processes in which we can change/modify the size of a data structure in runtime. It is not possible with Static Memory Allocation. Static memory allocation uses Stack memory to allocate the memory, while Dynamic Memory Allocation uses Heap memory to allocate the memory.
For dynamic memory allocation in C++ four functions are used, these are given below :
But in this article, we will only discuss the malloc() function. malloc() function is the function from stdlib library. malloc() function returns a pointer with void type and we need to type-cast it according to our requirement.
One example of malloc() is given below :
As you can see, we have allocated only 5*4=20 bytes but it can store more than 5 integers.
This is because the malloc function allocates a memory block of at least size bytes. The block may be larger than size bytes because of the space that’s required for alignment and maintenance information.
We should also need to free (deallocate) the used space after our requirement is fulfilled so that the memory leakage issue doesn’t appear.