Dynamic Memory Allocation in C – malloc(), calloc(), realloc() and free()

Suppose we have an array of length 5 named a shown below

Now during the length of the array (5) is fixed here. But what if we need to change the size of the array as per circumstances? It won’t be possible right?

Here comes the idea of dynamic memory allocation where we can change the size of the array shown above as per our need and whenever we need.

In case of static memory allocation there are some drawbacks like-wastage of memory, less flexibility, permanent allocation of variables etc. To overcome these situations the concept of dynamic memory allocation has been introduced. In dynamic memory allocation the memories can be allocated dynamically at run time.

So we can say that, The procedure of memory allocation in which the size of some particular data structures can be changed in runtime, is called Dynamic Memory Allocation (DMA).

For using dynamic memory allocation in C language, we need to include the standard library header file (stdlib.h) in our code.

Advantages of DMA?

1. The variables are allocated until the program unit gets inactive.

2. Unlike static memory allocation, memory allocation can be done during program execution (runtime).

3. It is more efficient than static memory allocation.

4. There is a flexibility in reusing the memory and memory can also be freed when required.

There 4 library functions that are described under stdlib.h:

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

Let’s read about them minutely.

1. malloc(): To allocate memory dynamically we use the function which is called as malloc() function. malloc() function on success returns the base address of the allocated memory on failure it returns the null value…(Read more in details)

2. calloc(): To allocate memory dynamically we also use the function which is called as calloc() function. calloc() function on success returns the base address of the array and every memory location will be initialized to 0…(Read more in details)

3. realloc(): At the time of memory allocation using calloc() or malloc(), it may be possible memory is excess or insufficient. So for that reason we need to reallocate memory at the run time…(Read more in details)

4. free(): The free() method in C is used to dynamically de-allocate the memory. It helps to reduce wastage of memory by freeing it…(Read more in details)

Follow Us

You Missed

Also Checkout