Dynamic Memory Allocation

Dynamic Memory Allocation is defined as a process where the size of a data structure can be modified during the run time.

There are certain predefined functions which can implement the above condition.There are 4 library functions provided by C all of which are defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.

They are:

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

malloc()

“malloc” or “memory allocation” method is used to allocate a single large block of memory baes on the specified size. The return type of malloc is of type void pointer which can be typecast-ed to any form.It initializes each block with a default value therefore some garbage value.

Syntax:

int *ptr = (cast-type*) malloc(byte-size)

For Example:  int *ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

calloc()

“calloc” or “contiguous allocation” method is used to allocate specified number of blocks of memory baes on the specified type. It initializes each block with a default value ‘0’.

Syntax:

int *ptr = (cast-type*)calloc(n, element-size);

For Example: int *ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the size of float.

free()

“free” method is used to de-allocate the memory or free the memory which was occupied by using the functions malloc() and calloc(),as they do not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Syntax:

free(ptr);

realloc()

“realloc” or “re-allocation” method is used to dynamically modify the memory allocation of a previously allocated memory. The memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.

Syntax:

int*ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'