Dynamic Memory

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:-

ptr_name = (cast-type *)malloc (size);
For Example:-

ptr = (int *)malloc (10 *sizeof(int));
On Successfully execution of this statement, a memory space equivalent to “10 times the size of int” byte is reserved and the address of the first byte of memory allocated is assigned to pointer ptr of type int. If the space is insufficient, allocation fails and returns a NULL pointer.

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:-

ptr_name = (cast-type *) calloc (n,size);
The above instruction allocates contiguous memory for n block, each of size byte.If the space is insufficient, allocation fails and returns NULL pointer.

For Example:-

ptr = (int *)calloc (10 ,sizeof(int));
This statement allocates contiguous space in memory for an array of 10 elements each of size of int.

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:-

free(ptr_name);
This statement free the space allocated in the memory pointed by ptr_name.

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

ptr_name = realloc(ptr_name, new-size);
This function allocates a new memory space of size new-size to the pointer variable ptr_name and returns a pointer to the first byte of the new memory block.

Recommended Tutorials: