Dma PDF
Dma PDF
MEMORY
ALLOCATION
1. SMA and DMA
2.Dalloc()
3.Calloc()
4.Realloc()
5.free()
Static memory allocation
• Memory is allocated during the compilation
of the program, not at runtime.
int a;
Example :
5 x 4 = 20 bytes
int arr[5]; 4 bytes is fixed
Dynamic memory
allocation
• Memory is allocated and deallocated at runtime,
as needed by the program. 1. malloc()
• The size of memory allocated can
2. calloc()
vary based on program requirements.
manually managed by
Lifetime until function returns
programmar
It returns a void* pointer, which needs to be cast to the desired pointer type
(e.g., int*, char*). If allocation fails (insufficient memory), it returns NULL.
Ex:
Syntax:
int *ptr;
void *malloc(size_t size);
ptr = (int*)malloc(5 * sizeof(int));
Ex:
4 bytes
int *ptr;
ptr = (int*)malloc(5 * sizeof(int));
ptr = 20 bytes
free(p);
return 0;
}
calloc()
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type
• It initializes each block with a default value ‘0’.
• It has two parameters or arguments as compare to malloc().
Syntax:
void *calloc( n , size_t size);
here, n is the no. of elements and size_t is the size of each element.
Ex:
int *ptr;
each blocks is 4 bytes
ptr = (int*)calloc(5 , sizeof(int));
3 6 9 0 5
void main()
{
int n,i,*p;
printf("Enter the number of elements:"); Enter the number of elements: 3
scanf("%d",&n);
0 0 0
p=(int *)calloc(n,sizeof(int));
free(p);
return 0;
}
Feature malloc calloc
size_t (number of
Arguments size_t (number of bytes) elements), size_t (element
size)
• maintains the already present value and new blocks will be initialized with the
default garbage value.
Syntax:
void *realloc( void *ptr , size_t size);
#include <stdio.h>
#include <stdlib.h>
Enter the number of elements: 2
void main() Enter values: 1
{
int n,i,*p;
2
printf("Enter the number of elements:"); Enter ubdated size of n: 4
scanf("%d",&n); Previous address = 11890256
p=(int *)malloc(n*sizeof(int)); New address= 11890256
The entered values are: 1 2 11862352 0
printf("Enter values: ");
for(i=0;i<n;i++){
scanf("%d",(p+i));
} 1 2
printf("Enter ubdated size of n:");
scanf("%d",&n);
int *ptr=(int *)realloc(p,n*sizeof(int));
printf("Previous address = %d\nNew address=
%d\n",p,ptr); 11890256 11890260 ............
free(ptr);
return 0;
free()
• “free” is used to dynamically de-allocate the memory.
Syntax:
free(pointer);
#include <stdio.h>
#include <stdlib.h> Enter the number of elements:3
Enter values: 1
void main()
{ 2
int n,i,*p; 3
printf("Enter the number of elements:");
scanf("%d",&n);
10186320
p=(int *)malloc(n*sizeof(int));
10186324
10186328
printf("Enter values: ");
for(i=0;i<n;i++){
scanf("%d",(p+i));
}
// free(p);
for(i=0;i<n;i++){
printf("%d\n",*(p+i));
}
free(p);
return 0;
}
THANK
YOU!