12.C_DYNAMIC_MEMORY_ALLOCATION
12.C_DYNAMIC_MEMORY_ALLOCATION
MEMORY ALLOCATION
MEMORY
ALLOCATION
STATIC DYNAMIC
MEMORY MEMORY
ALLOCATION ALLOCATION
STATIC MEMORY ALLOCATION
• array’s were used to allocate a fixed size of memory for our data.
• change it even if the size allocated is more or less than our requirement.
• For this, C has four built in functions under “stdlib.h” header files for
allocating memory dynamically.
STATIC AND DYNAMIC MEMORY
PRE-DEFINED FUNCTIONS
4 TYPES OF DMA FUNCTIONS
Function Purpose
Allocates the memory of requested
• 4 Types of DMA Functionssize and returns the pointer to the
malloc()
• 4 Types of DMA Functionsfirst byte of
allocated space.
Allocates the space for elements of
an array. Initializes the elements to
calloc()
zero and returns a pointer to the
memory.
• malloc () does not initialize the memory allocated during execution. It carries
garbage value.
#include <stdio.h>
#include <stdlib.h>
int main()
{ int* ptr ,n , i;
printf("Enter number of elements:);
scanf("%d",&n);
ptr = (int*)malloc(n*sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i)
ptr[i] = i + 1;
printf("The elements of the array are:"); // Print the elements of the array
for (i = 0; i < n; ++i)
printf("%d, ", ptr[i]);
}
free(ptr);
ptr=NULL;
return 0;
}
Calloc()[CONTIGUOUS ALLOCATION]
• calloc () function is also like malloc () function.
ptr=(cast-type*)calloc(number, byte-size)
Calloc()
EXAMPLE PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{ int* ptr ,n , i;
printf("Enter number of elements:);
scanf("%d",&n);
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i)
ptr[i] = i + 1;
printf("The elements of the array are:"); // Print the elements of the array
for (i = 0; i < n; ++i)
printf("%d, ", ptr[i]);
}
free(ptr);
ptr=NULL;
return 0;
}
free() FUNCTION
• “free” method in C is used to dynamically de-allocate the memory.
• The memory allocated using functions malloc() ,calloc() and realloc () is not de-
allocated on their own.
• Hence the free() method is used, whenever the dynamic memory allocation takes
place.
Syntax of free():
free(ptr);
realloc () [RE-ALLOCATION]
• realloc () function modifies the allocated memory size by malloc () and calloc ()
functions to new size.
• If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the full size of reallocation, then copies the existing data to new
block and then frees the old block.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr ,n1 ,n2, i;
printf("Enter size:);
scanf("%d",&n1);
ptr = (int*)malloc(n1*sizeof(int));
free(ptr);
ptr=NULL;
return 0;
}
THANK YOU
ANY QUERIES??