In a C program, we used various variables or arrays of primitive data types. When we declare such variables, the program assigns a predefined amount of memories and we cannot change the amount of the memories for that variable. i.e. Static Memory Allocation. But in some real life application may need to change the amount of memory regularly in real application may need to change the amount of memory regularly at real time.
E.g. create a name field for a banking project. Here we don’t know what will be the length of the name of a customer. If we get a char array for the name which length is 10. The it may too short for a south Indian customer. And also if we set the length of the variable is 100, then huge memory loss of most the customers.
To solve this problem C language uses some methods, like malloc(), calloc(), free(), realloc() to allocate memory at run time as per required. This type of memory allocation is known as Dynamic Memory Allocation which the size is changed during the runtime.
To allocate a specified size of memory block at runtime or dynamically, we use malloc(). Malloc is stands for memory allocation. It returns a pointer of type void. We can cast this pointer into any type or form.
Syntax:
ptr = (cast-type *) malloc(byte-size)
Example:
ptr = (int*) malloc(400);
This statement will allocate 400 bytes of memory. And *ptr hold the memory location or address of the first byte.
To allocate a numbers of memory block of specified size at runtime or dynamically, we use calloc(). Calloc is stands for contiguous allocation. It returns a pointer of type void. We can cast this pointer into any type or form.
Syntax:
ptr = (cast-type *) calloc(n,byte-size)
Example:
ptr = (int*) calloc(2,400);
This statement allocates contiguous space in memory for 2 elements each with the size of the 400 bytes that is total 800 bytes.