Dynamic Memory Allocation | malloc() | calloc() | free() | realloc() | BitsOfCS |

Dynamic Memory Allocation:

When we need to change the size of data structure at runtime, then we use dynamic memory allocation. C language provides some functions for dynamic memory allocation. There are 4 library functions in C language that are defined under the ‘stdlib.h’ header file to facilitate dynamic memory allocation.

  1. malloc()

  2. calloc()

  3. free()

  4. realloc()

In order to use dynamic memory allocation, a heap segment is used.


1. malloc() :

We use ‘malloc’ or ‘memory allocation’ to dynamically allocate a single large block of memory with the given size. This function returns a pointer of ‘void’ type, later on we can cast this pointer into a pointer of any type. 

Syntax: pointer = (cast_type *)malloc(byte_size);

Example: 


In the allocated memory, ‘ptr’ pointer have the address of the first byte. If allocation fails, hence the space is insufficient, then this function returns a NULL pointer. 


2. calloc() :

We can use the ‘calloc’ or ‘continuous allocation’ function to dynamically allocate the specified number of blocks of memory of the specified type. This function initializes each block with the default value ‘0’. 

Syntax: pointer = (cast_type *)malloc(n, element_size);

Example: 

 



If the space is insufficient, then allocation will fail and this function returns a NULL pointer.


3. free() :

After dynamically allocation of the memory, in order to have a good programming habit, we must dynamically deallocate the memory. The memory allocated by the function malloc() and calloc() will not deallocate on their own. 

Hence, we can use free() whenever memory allocation takes place. This function helps to reduce the wastage of memory, by freeing it.

Example: 


4. realloc() :

Let’s consider a situation, we used any function either malloc() or calloc() to dynamically allocate the memory. But now we want to change the specified size of the previously allocated memory because it becomes insufficient. Then we can use, realloc() function to dynamically re-allocate the memory.

Syntax: pointer = realloc(pointer, new_size);

Here ‘pointer’ will be re-allocated with the new size. This function will return NULL, if allocation fails, hence the space is insufficient.

Example: 



The size of the ‘ptr’ is dynamically changed from 20 bytes to 40 bytes. 

If you find any problem related to this article, please comment below or contact me here.


manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.