C 7
C 7
• Memory allocation
• Static Memory Allocation
• Memory Allocation Process
• Memory Allocation Functions
• Allocation A Block Of Memory : Malloc
• Allocation A Block Of Memory : Calloc
• Altering The Size Of A Block : Realloc
• Releasing The Used Space: Free
MEMORY ALLOCATION
• In memory allocation has two types. They are static and dynamic
memory allocation.
STATIC MEMORY ALLOCATION
Ptr=(cast-type*)calloc(n,elem-size);
EXAMPLE PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{ output:
int i, n;
int *a; Number of elements to be entered :3
printf("Number of elements to be entered:"); Enter 3 numbers:
scanf("%d",&n); 22
a = (int*)calloc(n, sizeof(int)); 55
printf("Enter %d numbers:\n",n); 14
for( i=0 ; i < n ; i++ ) The numbers entered are :22 55 14
{
scanf("%d",&a[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ )
{
printf("%d ",a[i]);
}
free( a );
return(0);
}
ALTERING THE SIZE OF A BLOCK : REALLOC
ptr=REALLOC(ptr,new size);
EXAMPLE PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{ Output:
int *ptr = (int *)malloc(sizeof(int)*2);
int i; 10 20 30
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i < 3; i++)
printf("%d ", *(ptr_new + i));
return 0;
}
RELEASING THE USED SPACE: FREE
Free() function should be called on a pointer that was used either with
”calloc()” or “malloc()”,otherwise the function will destroy the memory
management making a system to crash.
free (ptr)
EXAMPLE:
func()
{
int *ptr, *p;
ptr = new int[100];
p = new int;
delete[] ptr;
delete p;
}