Dynamic Memory Allocation by SA
Dynamic Memory Allocation by SA
Presented by:
Shambhavi Agrawal
CS-2
12/23/2024 1
Table of Contents
• Memory Allocation
• Types of Memory Allocation
– Static Memory Allocation
– Dynamic Memory Allocation
• calloc() function
• malloc() function
• realloc() function
• free() function
• References
12/23/2024 2
Memory Allocation
• Memory allocation is a process by which computer
programs and services are assigned with physical or
virtual memory space
• Memory allocation is achieved through a process known
as memory management
• To allocate memory it is necessary to keep in information
of available memory in the system. If memory
management system finds sufficient free memory, it
allocates as much memory as needed
12/23/2024 3
Types of memory allocation
12/23/2024 4
Dynamic Memory Allocation
• Whenever we define any array in a program, the fixed
block of memory is assigned to that array. This happens
through static memory allocation process. It creates a
problem when we do not have fixed number of elements
to be stored
• Pointer can be used to with array to resolve this problem
and to provide facility of dynamic array.
• Dynamic memory allocation is the process of providing
memory blocks to the variables at execution time of
program
12/23/2024 5
• To perform different memory allocation ,different
memory allocation method such as malloc(), calloc(),
realloc(),free()
12/23/2024 7
Example
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
Output
}
printf("Enter elements of array: "); Enter elements of elements: 3
for(i=0;i<n;++i) Enter elements of array: 10 10 10
{ Sum=30
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
12/23/2024 8
}
calloc() function
12/23/2024 9
realloc() function
12/23/2024 10
free() function
12/23/2024 11
References
• https://www.javatpoint.com/dynamic-memory-allocation-i
n-c
• https://www.geeksforgeeks.org/dynamic-memory-allocatio
n-in-c-using-malloc-calloc-free-and-realloc/
• https://www.geeksforgeeks.org/what-is-dynamic-memory
12/23/2024 12
Thank You
12/23/2024 13