malloc
Using the malloc function we can allocate the required amount of memory in byte size. This memory is available as an array.
Syntax:
pointer_variable=(type*)malloc(size);
pointer_variable->represents the pointer variable given in our program.
type->malloc specifies what type the function returns. It is a pointer variable.
malloc-->malloc is a keyword.
Size--> refers to the amount of memory we need.
This function takes the required amount of memory and returns its starting memory address through a pointer variable called type.
Eg:
int*x;
x=(int*)malloc(10*sizeof(int));
The value of sizeof(int) is 4 bytes, then the value of malloc(10*sizeof(int)) is 40 bytes.
40 bytes of memory is created in memory and its starting memory address is given to the pointer variable called x.
calloc
An extension of calloc is contiguous allocation. More than one memory can be allocated sequentially using the calloc function.
Syntax:
pointer_variable=(type*)calloc(n,size);
n->how many elements to create memory for.
Size-> How much memory should be given to each element created.
This function creates memory blocks of size n.
The memory blocks created are of the size we give.
Its starting address is returned by a pointer called type. Zero value is given to all the memory blocks created.
Eg:
Y=(int*)calloc(2,7);
What is said in this statement is that 2 memory blocks of 7 bytes size are created. Its starting address is given to the pointer variable called y.
realloc
The size of dynamic memory created by malloc and calloc can be changed using the realloc function.
This function is inside the stdio.h header file.
Syntax:
pointer_variable=realloc(old pointer_variable,new size);
new size->required size of new memory. This function creates new memory for the given new size.
Creates its starting address. Returns its starting address to the pointer variable.
Eg:
int*x;
x=(int*)malloc(5*sizeof(int));
x=realloc(x,40);