C requires the number of elements in the array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause the failure of the program or wastage of memory. The process of allocating memory at run time is known as dynamic memory allocation. Dynamic memory management technique permits us to allocate additional memory or release unwanted memory at run time, thus optimizing the use of storage memory.
C does not have inherently have this facility there are four library functions known as”Memory management functions” that can be used for allocating and freeing memory at run time.
Malloc:-
A block of memory may be allocated using the function malloc. The malloc function reserves a memory block of memory of specified size and returns a pointer of type void. This means we can assign it any type of pointer. It takes the following form:-
Calloc:-
It is another memory allocating function that is normally used for requesting memory at run time for storing data type like array and structure.While malloc allocates a single block of memory, calloc allocates multiple blocks of storage, each of the same size and then sets all byte to zero.A general form of calloc is:-
For Example:-
Releasing the used memory:-Free function
Compile-time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic run-time allocation, its our responsibility to release the memory when it is not required. We may release the block of memory for future use, using the free function. A general form of free is:-
Realloc:-
When we need additional memory for more elements because our previously allocated memory is not sufficient or allocated memory is much larger than necessary and we want to reduce it.In both cases, we can change the memory size of allocated memory with help of realloc function.A general form of realloc is
Recommended Tutorials: