calloc() and free() Function in C

Notes:

calloc() and free() Function in C Programming Language:

calloc() function:
- calloc stands for contiguous allocation
- It allocates n memory blocks of a given size in bytes contiguously i.e. an array of memory blocks
- Each allocated memory block contains collection of memory locations each of size one byte
- Each memory location inside the allocated memory blocks is initialized with value Zero
- On success of memory allocation; It returns beginning address of the array of memory blocks
- if the allocation fails it returns NULL value

Syntax or prototype of calloc() function is:
(void *) calloc (size_t n, size_t sizeInBytes);

where :
void * : indicates a generic pointer type which can be converted to any specific pointer type
size_t : indicates unsigned integer value i.e +ve integer value
n : indicates number of blocks to be allocated contiguously
sizeInBytes : indicates size of each memory block to be allocated in bytes

Ex 1: calloc (1, sizeof(int));
It allocates 1 memory block of size 4 bytes and returns beginning address of the allocated memory block as a generic pointer type value

Ex 2: calloc (5 , sizeof(int));
It allocates 5 memory blocks each of size 4 bytes contiguously and returns beginning address of the array of memory blocks as a generic pointer type value

Example Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *iptr = NULL;

iptr = (int *) calloc(5, sizeof(int));

*(iptr + 0) = 10; // *( #20 ) = 10;
*(iptr + 1) = 11; // *(#24) = 11;
*(iptr + 2) = 12; // *(#28) = 12;
*(iptr + 3) = 13; // *(#32) = 13;
*(iptr + 4) = 14; // *(#36) = 14;

printf("Value of #20 = %d\n", *(iptr + 0)); // 10
printf("Value of #24 = %d\n", *(iptr + 1)); // 11
printf("Value of #28 = %d\n", *(iptr + 2)); // 12
printf("Value of #32 = %d\n", *(iptr + 3)); // 13
printf("Value of #36 = %d\n", *(iptr + 4)); // 14

free(iptr);
iptr = NULL;

return 0;
}