C language requires the no of elements in an array to be specified at compile time.But we may not be able to do so always our initial judgement of size,if it is wrong,it make cause failure of the program (or) wastage of the memory space.In this situation we use Dynamic Memory allocation.
Definition:-The process of allocating memory at run time is known as Dynamic memory allocation.
Malloc():- <alloc.h>
It is a function which is used to allocating memory at run time.
Syntax:- void *malloc(size_t size);
size_t:- unsigned integer. this is used for memory object sizes.
Pointer variable=(type casting)malloc(memory size);
Example:- int *p;
p=(int *)malloc(sizeof(int)); //for 1 location
p=(int *)malloc(n*sizeof(int)); //for n locations
Calloc():- <alloc.h>
This is also used for allocating memory at run time.
Syntax: void *calloc(size_t nitems, size_t size);
NOTE:- Calloc allocates a block (n times*size)bytes and clears into 0.
Difference between malloc and calloc:
- Malloc default store garbage value where as calloc default stores zero
- In malloc only one argument we will pass where as in calloc we will pass two arguments
Program:Write a program to create a dynamic array (vector) store values from keyboard display #include<stdio.h> #include<conio.h> #include<malloc.h> void main() { int *a,n,i; clrscr(); printf("Enter no of elements:"); scanf("%d",&n); a=(int *)malloc(n* sizeof(int)); //a=(int ) calloc(n,sizeof(int)); printf("Enter array elements:"); for(i=0;i<n;i++) { scanf("%d",a+i); } printf("Given array elements:"); for(i=0;i<n;i++) { printf("%d\t",*(a+i)); } getch(); }
Realloc():- It reallocates Main memory.
Syntax:- void *realloc(void *block, size_t size);
free():- It deallocates the allocated memory.
Syntax:- void free(void *block);
Program:Write a program to demonstrate reaclloc #include<stdio.h> #include<conio.h> #include<alloc.h> #include<string.h> void main() { char *str; clrscr(); str=(char *)malloc(8); strcpy(str,"Hello"); printf("String is %s",str); str=(char *)realloc(str,25); strcat(str," demonstration of realloc"); printf("\n New string is %s",str); free(str); getch(); }