C Dynamic Memory Allocation

The main concept of dynamic memory allocation in c language enables the programmer to allocate memory at runtime. In C, dynamic memory is allocated from the heap using some standard library functions.
These are library functions:

  • malloc()
  • calloc()
  • realloc()
  • free()
Function syntax
malloc() malloc (number *sizeof(int));
calloc() calloc (number, sizeof(int));
realloc() realloc (pointer_name, number * sizeof(int));
free() free (pointer_name);

malloc()

This function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. It takes a single argument that is the amount of memory to allocate in bytes but does not initialize the memory allocated.

Syntax

In the above example, memory is allocated for space of size 8 bytes to store 8 characters.

Example

Output

calloc()

The calloc function stands for contiguous allocation. calloc () function is also like malloc () function. But calloc() initializes the specified bytes to zero.

syntax:

In the above example, memory is allocated for space of size 8 bytes to store 8 characters.

Example

Output

When the program no longer needs the dynamic array, it eventually calls free to return the memory it occupies. The malloc function returns NULL value if it fails to allocate the specified memory space. calloc() needs two arguments that are the number of variables to allocate in memory and the size in bytes of a single variable.

Output

realloc()

realloc stands for reallocation of memory. realloc function is used to change the memory size of the previously allocated memory space or we can say that it increases or decreases the size of block of memory that is specified to use and also realloc moves it’s if necessary.

Syntax

Example

Output

free()

The free() function is called to release/deallocate memory. it releases the specified block of memory and returns it back to the system. It frees the allocated memory of malloc (), calloc (), realloc () function because these function do not get freed on their own.

Syntax:

free (pointer_name); //it does not have return type

Example

Output