90 likes | 628 Views
Memory allocation functions:. There are two types of memory allocations in C Static Memory Allocation Dynamic Memory Allocation 1. Static Memory Allocation
E N D
Memory allocation functions: There are two types of memory allocations in C Static Memory Allocation Dynamic Memory Allocation 1. Static Memory Allocation The process of allocating memory at compile time is called “static memory allocation”. The memory reserved in this static memory allocation and it can’t be changed during runtime
. 2. Dynamic Memory Allocation:- • The process of allocating memory at runtime is called dynamic memory allocation • We can change the memory allocations for each execution of a program • This allocation avoids the wastage of memory space stack heap permanent storage area
. • The program instructions and global variables are stored in an area in memory called “Permanent Storage Area”. • The local variables stored in memory are called “Stack” • The area between stack and permanent storage is called “Heap” which is used for dynamic memory allocation. Dynamic memory allocation can be done using following functions 1.malloc 2.calloc 3.realloc 4.free
. • malloc(Memory Allocation Function): The malloc() function is used to allocate a single block of memory with a specified size. As the memory allocated in heap we can access the data through pointers. Syntax:- pntr=(cast type*)malloc(byte size); where pointer is a pointer variable and byte size is the total no of bytes to be allocated at runtime. eg:- int*a; a=(int*)malloc(20);
. //program to illustrate dynamic memory // allocation functions using malloc() void main() { int n,*a,i; printf(“\n Enter the size of an array:”); scanf(“%d”,&n); a=(int*)malloc(n*sizeof(int)); for(i=0;i<n;i++) { printf(“\n Enter the element”); scanf(“%d”,a+i); } for(i=0;i<n;i++) printf(“\t%d”,*(a+i)); free(a); }
. 2. calloc(multiple blocks of memory):- • The function is used to allocate multiple blocks of memory / storage • By default all the locations will be initialized to zero • It is specifically used to store structures syntax: pntr=(casttype*)calloc(n,size); n=no of blocks size=no of bytes to be allocated to each block
. 3. realloc(reallocation of memory):- This function is used to increase/decrese the size of already allocated memory. Syntax:-pntr=(casttype*)realloc(pntr,newsize); 4. free: This is used to release the memory allocation at run time. Syntax: free(pntr);
. //program to illustrate about dynamic memory //allocation using function realloc() void main() { char*c; c=(char*)malloc(10); c=“SREYAS”; printf(“\n%s”,c); c=(char*)realloc(c,20); c=“SREYAS @ HYDERABAD”; printf(“\n%s”,c); free(c); }