C - Dynamic Memory Allocation

C - Dynamic Memory Allocation in C programming, how to use calloc() and malloc() in c programming, C - Dynamic Memory Allocation

Let's take an example of array declaration on C programming.

 int z[25] 
It reserves memory space for 25 integer numbers, Sometimes, the problem arises with this declaration. If the user needs to work on more than 25 values the allocated memory will not be sufficient.

Besides, if the user needs to work on less than 25 values the allocated memory will be unused. This types of allocating memory at compile time is called static memory allocation.

To maintain the limitation of the memory for array elements can be allocated at the run time. The first address of the allocated memory is assigned to the pointer variable which can subsequently by used as an array. The memory allocation at run time is called dynamic memory allocation. 

 C language provides functions such as malloc() and malloc() for dynamic memory allocation and free() to deallocate the allocated memory.

The function prototypes for these functions are in the header file. The name calloc() stands for "contiguous allocation" and malloc() stands for "memory allocation". The pointer returned by callous() or malloc() is type of void* so it must be cast into the appropriate type. The malloc() function is used as
int *ip;
ip = (int*) calloc(n, sizeof(int));
The calloc() function takes two arguments, the first argument is the number of items and the second argument is the size of each item for which the memory is to be allocated. The calloc() function also initializes the allocated memory to zero. the function malloc() is used as,
int *ip;
ip = (int *) malloc (n * sizeof(int));
The malloc() function takes one argument that specifies the total memory to be allowed. So to allocate memory for n integer, the argument is passed as n*sizeof(int). and same as calloc(), malloc() doesn't initialize the allocated memory and is rather than calloc().

You May Also Like...

Subscribe Us