Dynamic memory allocation

Dynamic Memory Allocation :

Dynamic Memory Allocation is used to dynamically allocate memory at runtime.
There are 4 methods in C that are used for dynamic memory allocation in C :

  1. malloc ()
  2. calloc ()
  3. realloc ()
  4. free ()

malloc () :

This function allocates the blocks of memory required and returns a pointer of void type pointing to the first byte of allocated memory, if successful else returns NULL.
 
Syntax  : void* malloc(required_size);

Example :

Output :

calloc () :

This function allocates the blocks of memory required as well as initialises them to 0 and returns a pointer of void type pointing to the first byte of allocated memory, if successful else returns NULL.
 
Syntax  : void* calloc(n, size_of_an_element);
Example :


Output :

Difference between calloc() and malloc() :

malloc() calloc()
It allocates a single block of memory.  It allocates a contiguous block of memory having same size.
It takes a single parameter i.e. total size to be allocated.  It takes two parameters ,no of blocks required and size of each.
Memory locations contain garbage values.  It initializes the value to 0.

realloc () :

If the size of memory is insufficient or not available ,it can be reallocated or  the size of previously allocated space can be modified using realloc function.

If enough space doesn’t exist in memory of current block to extend, new block is allocated for the full size of reallocation, then copies the existing data to new block and then frees the old block.

If it fails to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged).

Syntax  : void* realloc(ptr, new size);

Example :


Output :

free() :

This function deallocates the memory reserved by malloc, calloc, realloc functions, making it available for further allocations.

Syntax  : void free(ptr);

Leave a Reply

Your email address will not be published. Required fields are marked *