The process of allocating memory to the variables during execution of the program or at run time is known as dynamic memory allocation.
C language provides a mechanism of dynamically allocating memory that is actually required. We reserve space only at run time for the variable that are actually required.
C provides four library functions to automatically allocate memory at the run time. All these functions are discussed below.
1.) Allocating a block of memory using malloc() function
This function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. The general syntax of malloc() is
pointer-variable = (cast-type*)malloc(n*sizeOf(byte-size));
Example1:
#include<stdio.h> #include<stdlib.h> void main() { int i,n; int *arr; // creating an array using pointer printf(" enter number of elements"); scanf("%d",&n) arr=(int*)malloac(n*sizeOf(int); if(arr= = NULL) printf(" memory not allocated"); printf(" enter elements into array"); for(i=0;i<n;i++) scanf("%d",&arr[i]); printf(" array contains elements"); for(i=0;i<n;i++) printff("%d",arr[i]); free(arr); getch(); }
2.) Allocating multiple blocks of memory using calloc() function
The function calloc() is another function that reserves memory at the run time. It is normally used to request multiple blocks of storage each of the same size and then set all bits to zero. The general syntax of calloc() is
pointer-variable = (cast-type*)calloc(n*sizeOf(byte-size));
Example2:
#include<stdio.h> #include<stdlib.h> void main() { int i,n; int *arr; // creating an array using pointer printf(" enter number of elements"); scanf("%d",&n) arr=(int*)calloac(n*sizeOf(int); if(arr= = NULL) printf(" memory not allocated"); printf(" enter elements into array"); for(i=0;i<n;i++) scanf("%d",&arr[i]); printf(" array contains elements"); for(i=0;i<n;i++) printff("%d",arr[i]); free(arr); getch(); }
3. Re-allocating memory using realloc()
The memory allocated by using malloc() and calloc() might be insufficient in some cases. In both situations we can always use realloc() to change the memory size already allocated. This process is called reallocation of memory.
pointer-variable = (cast-type*)realloc(pointer variable, new size);
Example3:
#include<stdio.h> #include<stdlib.h> #include<string.h> void main() { char *str; str=(char*)malloc(10); if(str==NULL) printf(" memory not allocated"); strcpy(str,"hi"); puts(str); prinft(" I am reaalocating string memory"); str=(char*)realloc(str,20); strcpy(str,"hi hello"); puts(str); free(str); getch();
4. free() function
when we are dynamically allocating memory then it is our responsibility to release the space when it not required. Using free() function one can do this.
Syntax: free( pointer variable);
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.