SlideShare a Scribd company logo
1 of 26
Dynamic Memory Allocation
Presented By
Mrs.B.Vijayalakshmi, AP(SG)/CSE
Ramco Institute of Technology
Dynamic Memory Allocation
• The process of allocating memory during run
time(Execution time) is known dynamic
memory allocation.
• The memory for dynamically allocated
variables are allocated on the heap.
• Ability of a program to use more memory
space at execution time
• Memory space required can be specified at
the time of execution.
• C supports allocating and freeing memory
dynamically using library routines.
• These functions are available in stdlib.h
Memory Allocation Functions
• malloc – Allocates requested number of bytes
and returns a pointer to the first byte of the
allocated space.
• calloc – Allocates space for an array of
elements, initializes them to zero and then
returns a pointer to the memory.
• Free- Frees previously allocated space.
• realloc – Modifies the size of previously
allocated space.
malloc()
• The name "malloc" stands for memory
allocation.
• The malloc() function reserves a block of
memory of the specified number of bytes.
• It returns a pointer of void which can be
casted into pointers of any form.
Syntax of malloc()
• voidptr = (castType*) malloc(size);
Examples
• int *p;
• p = (int *) malloc (100 * sizeof (int)) ;
• A memory space equivalent to “100 times the
size of an int” bytes is reserved.
• The address of the first byte of the allocated
memory is assigned to the pointer p of type
int.
P
Example
• float *ptr;
• ptr = (float*) malloc(100 * sizeof(float));
• The above statement allocates 800 bytes of
memory. It's because the size of float is 8
bytes.
• And, the pointer ptr holds the address of the
first byte in the allocated memory.
Write statements
• Allocate memory of storing 50 integers
• Allocate memory of storing 40 characters
• Allocate memory of storing 120 double values
• Allocate memory of storing 150 floating point
values
Answers
• Allocate memory of storing 50 integers
iVar=(int*)malloc(50*sizeof(int));
• Allocate memory of storing 40 characters
cVar=(char*)malloc(40*sizeof(char));
• Allocate memory of storing 120 double values
dVar=(double*)malloc(120*sizeof(double));
• Allocate memory of storing ‘n’ floating point values
fVar=(float*)malloc(n*sizeof(float));
Example
int*ip;
ip= (int*) malloc(10 * sizeof(int));
If (ip== NULL)
{
printf("Insufficient Memory, Exiting... n");
return 0;
}
C program to create memory for int,
char and float variable at run time.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *iVar;
char *cVar;
float *fVar;
/*allocating memory dynamically*/
iVar=(int*)malloc(1*sizeof(int));
cVar=(char*)malloc(1*sizeof(char));
fVar=(float*)malloc(1*sizeof(float));
printf("Enter integer value: ");
scanf("%d",iVar);
printf("Enter character value: ");
scanf(" %c",cVar);
printf("Enter float value: ");
scanf("%f",fVar);
printf("Inputted value are: %d, %c,
%.2fn",*iVar,*cVar,*fVar);
/*free allocated memory*/
free(iVar);
free(cVar);
free(fVar);
return 0;
}
• voidptr = (castType*) malloc(size);
• Void pointer- any type accepted
• Return value is a pointer to the beginning of
the block of memory allocated.
• It returns NULL pointer if it could not able to
allocate requested amount of memory.
• It does not initialize the memory allocated
during execution. It carries garbage value.
C program to input and print text
using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
char *text;
printf("Enter limit of the text: ");
scanf("%d",&n);
/*allocate memory dynamically*/
text=(char*)malloc(n*sizeof(char));
printf("Enter text: ");
gets(text);
printf("Inputted text is: %sn",text);
/*Free Memory*/
free(text);
return 0;
}
Output:
Enter limit of the text: 100
Enter text: Welcome to C
Programming.
Inputted text is: Welcome to C
Programming.
Program to calculate the sum of n
numbers entered by the user
#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));
// if memory cannot be allocated
if(ptr == NULL)
{
printf("Error! memory not
allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
C program to read and print the student details
using structure and Dynamic Memory
Allocation.
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[30];
int roll;
float perc;
};
int main()
{
struct student *pstd;
/*Allocate memory dynamically*/
pstd=(struct student*)malloc(1*sizeof(struct student));
if(pstd==NULL)
{
printf("Insufficient Memory,
Exiting... n");
return 0;
}
/*read and print details*/
printf("Enter name: ");
gets(pstd->name);
printf("Enter roll number: ");
scanf("%d",&pstd->roll);
printf("Enter percentage: ");
scanf("%f",&pstd->perc);
printf("nEntered details
are:n");
printf("Name: %s, Roll
Number: %d, Percentage:
%.2fn",pstd->name,pstd-
>roll,pstd->perc)
return 0;
}
Output:
Enter name: Mike
Enter roll number: 1
Enter percentage: 87.50
Entered details are:
Name: Mike, Roll Number: 1,
Percentage: 87.50
C program to read and print the N student
details using structure and Dynamic Memory
Allocation
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[30];
int roll;
float perc;
};
int main()
{
struct student *pstd;
int n,i;
printf("Enter total number of
elements: ");
scanf("%d",&n);
/*Allocate memory dynamically for n
objetcs*/
pstd=(struct
student*)malloc(n*sizeof(struct
student));
if(pstd==NULL)
{
printf("Insufficient Memory,
Exiting... n");
return 0;
}
/*read and print details*/
for(i=0; i<n; i++)
{
printf("nEnter detail of
student [%3d]:n",i+1);
printf("Enter name: ");
scanf(" "); /*clear input
buffer*/
gets((pstd+i)->name);
printf("Enter roll number:
");
scanf("%d",&(pstd+i)->roll);
printf("Enter percentage: ");
scanf("%f",&(pstd+i)->perc);
}
printf("nEntered details
are:n");
for(i=0; i<n; i++)
{
printf("nEntered details
are:n"); for(i=0; i<n; i++) {
printf("%30s t %5d t
%.2fn",(pstd+i)->name,(pstd+i)-
>roll,(pstd+i)->perc); }
return 0;}
calloc()
• The name "calloc" stands for contiguous allocation.
• calloc() allocates multiple blocks of memory each of
same size and sets all bytes to zero.
• calloc() takes two arguments:
– the number of blocks to be allocated
– the size of each block (in bytes)
• calloc() returns the address of the chunk of memory
that was allocated
• calloc() also sets all the values in the allocated memory
to zeros
• calloc()is also used to dynamically allocate arrays
Syntax and Example
Syntax:
ptr = (castType*)calloc(n, size);
Example 1:
• ptr = (float*) calloc(25, sizeof(float));
• The above statement allocates contiguous space in memory
for 25 elements of type float.
Example2:
For instance, to dynamically allocate an array of 10 ints:
• int*arr;
• arr= (int*) calloc(10, sizeof(int));
• /* now arrhas the address
• of an array of 10 ints, all 0s */
Difference between malloc() and
calloc()
• malloc() allocates single block of memory
whereas leaves the memory uninitialized.
• calloc() function allocates multiple blocks of
memory of same size and initializes all bits to
zero.
free()
• Dynamically allocated memory created with
either calloc() or malloc() doesn't get freed on
their own.
• You must explicitly use free() to release the
space.
Syntax of free()
free(ptr);
• This statement frees the space allocated in the
memory pointed by ptr.
Program to calculate the sum of n numbers
entered by the user using calloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements:
");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not
allocated.");
exit(0); }
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Realloc
• It is used to dynamically change the memory
allocation of a previously allocated memory.
• If the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory.
Syntax:
• ptr= realloc(ptr, num_bytes);
• where ptr is reallocated with new size 'newSize'.
–Find space for new allocation
–Copy original data into new space
–Free old space
–Return pointer to new space
Dynamically Allocating 2D Array
float **A; /* A is an array (pointer) of float pointers */
int I;
A = (float **) calloc(5,sizeof(float *));
/* A is a 1D array (size 5) of float pointers */
for (I = 0; I < 5; I++)
A[I] = (float *) calloc(4,sizeof(float));
/* Each element of array points to an array of 4 float variables */
/* A[I][J] is the Jth entry in the array that the Ithmember of A
points to */

More Related Content

What's hot (20)

Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
C functions
C functionsC functions
C functions
 
Strings in c
Strings in cStrings in c
Strings in c
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Strings in C
Strings in CStrings in C
Strings in C
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Strings
StringsStrings
Strings
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Structure in C
Structure in CStructure in C
Structure in C
 
File in C language
File in C languageFile in C language
File in C language
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

Similar to Dynamic memory allocation

Similar to Dynamic memory allocation (20)

dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
Memory management CP
Memory management  CPMemory management  CP
Memory management CP
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
Dma
DmaDma
Dma
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Dynamic allocation
Dynamic allocationDynamic allocation
Dynamic allocation
 
DMA.pptx
DMA.pptxDMA.pptx
DMA.pptx
 

More from Viji B

Heap Memory Management.pptx
Heap Memory Management.pptxHeap Memory Management.pptx
Heap Memory Management.pptxViji B
 
ML & AI based Cloud Compiler.pptx
ML & AI based Cloud Compiler.pptxML & AI based Cloud Compiler.pptx
ML & AI based Cloud Compiler.pptxViji B
 
Innovative pratice crossword
Innovative pratice crosswordInnovative pratice crossword
Innovative pratice crosswordViji B
 
Innovative practice role play sorting
Innovative practice role play sortingInnovative practice role play sorting
Innovative practice role play sortingViji B
 
Innovative Practice- Learning by doing- Complete the code and trace the exec...
Innovative  Practice- Learning by doing- Complete the code and trace the exec...Innovative  Practice- Learning by doing- Complete the code and trace the exec...
Innovative Practice- Learning by doing- Complete the code and trace the exec...Viji B
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree dsViji B
 

More from Viji B (6)

Heap Memory Management.pptx
Heap Memory Management.pptxHeap Memory Management.pptx
Heap Memory Management.pptx
 
ML & AI based Cloud Compiler.pptx
ML & AI based Cloud Compiler.pptxML & AI based Cloud Compiler.pptx
ML & AI based Cloud Compiler.pptx
 
Innovative pratice crossword
Innovative pratice crosswordInnovative pratice crossword
Innovative pratice crossword
 
Innovative practice role play sorting
Innovative practice role play sortingInnovative practice role play sorting
Innovative practice role play sorting
 
Innovative Practice- Learning by doing- Complete the code and trace the exec...
Innovative  Practice- Learning by doing- Complete the code and trace the exec...Innovative  Practice- Learning by doing- Complete the code and trace the exec...
Innovative Practice- Learning by doing- Complete the code and trace the exec...
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 

Recently uploaded (20)

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 

Dynamic memory allocation

  • 1. Dynamic Memory Allocation Presented By Mrs.B.Vijayalakshmi, AP(SG)/CSE Ramco Institute of Technology
  • 2. Dynamic Memory Allocation • The process of allocating memory during run time(Execution time) is known dynamic memory allocation. • The memory for dynamically allocated variables are allocated on the heap.
  • 3. • Ability of a program to use more memory space at execution time • Memory space required can be specified at the time of execution. • C supports allocating and freeing memory dynamically using library routines. • These functions are available in stdlib.h
  • 4. Memory Allocation Functions • malloc – Allocates requested number of bytes and returns a pointer to the first byte of the allocated space. • calloc – Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. • Free- Frees previously allocated space. • realloc – Modifies the size of previously allocated space.
  • 5. malloc() • The name "malloc" stands for memory allocation. • The malloc() function reserves a block of memory of the specified number of bytes. • It returns a pointer of void which can be casted into pointers of any form. Syntax of malloc() • voidptr = (castType*) malloc(size);
  • 6. Examples • int *p; • p = (int *) malloc (100 * sizeof (int)) ; • A memory space equivalent to “100 times the size of an int” bytes is reserved. • The address of the first byte of the allocated memory is assigned to the pointer p of type int. P
  • 7. Example • float *ptr; • ptr = (float*) malloc(100 * sizeof(float)); • The above statement allocates 800 bytes of memory. It's because the size of float is 8 bytes. • And, the pointer ptr holds the address of the first byte in the allocated memory.
  • 8. Write statements • Allocate memory of storing 50 integers • Allocate memory of storing 40 characters • Allocate memory of storing 120 double values • Allocate memory of storing 150 floating point values
  • 9. Answers • Allocate memory of storing 50 integers iVar=(int*)malloc(50*sizeof(int)); • Allocate memory of storing 40 characters cVar=(char*)malloc(40*sizeof(char)); • Allocate memory of storing 120 double values dVar=(double*)malloc(120*sizeof(double)); • Allocate memory of storing ‘n’ floating point values fVar=(float*)malloc(n*sizeof(float));
  • 10. Example int*ip; ip= (int*) malloc(10 * sizeof(int)); If (ip== NULL) { printf("Insufficient Memory, Exiting... n"); return 0; }
  • 11. C program to create memory for int, char and float variable at run time. #include <stdio.h> #include <stdlib.h> int main() { int *iVar; char *cVar; float *fVar; /*allocating memory dynamically*/ iVar=(int*)malloc(1*sizeof(int)); cVar=(char*)malloc(1*sizeof(char)); fVar=(float*)malloc(1*sizeof(float)); printf("Enter integer value: "); scanf("%d",iVar); printf("Enter character value: "); scanf(" %c",cVar); printf("Enter float value: "); scanf("%f",fVar); printf("Inputted value are: %d, %c, %.2fn",*iVar,*cVar,*fVar); /*free allocated memory*/ free(iVar); free(cVar); free(fVar); return 0; }
  • 12. • voidptr = (castType*) malloc(size); • Void pointer- any type accepted • Return value is a pointer to the beginning of the block of memory allocated. • It returns NULL pointer if it could not able to allocate requested amount of memory. • It does not initialize the memory allocated during execution. It carries garbage value.
  • 13. C program to input and print text using Dynamic Memory Allocation #include <stdio.h> #include <stdlib.h> int main() { int n; char *text; printf("Enter limit of the text: "); scanf("%d",&n); /*allocate memory dynamically*/ text=(char*)malloc(n*sizeof(char)); printf("Enter text: "); gets(text); printf("Inputted text is: %sn",text); /*Free Memory*/ free(text); return 0; } Output: Enter limit of the text: 100 Enter text: Welcome to C Programming. Inputted text is: Welcome to C Programming.
  • 14. Program to calculate the sum of n numbers entered by the user #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)); // if memory cannot be allocated if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); // deallocating the memory free(ptr); return 0; }
  • 15. C program to read and print the student details using structure and Dynamic Memory Allocation. #include <stdio.h> #include <stdlib.h> struct student { char name[30]; int roll; float perc; }; int main() { struct student *pstd; /*Allocate memory dynamically*/ pstd=(struct student*)malloc(1*sizeof(struct student));
  • 16. if(pstd==NULL) { printf("Insufficient Memory, Exiting... n"); return 0; } /*read and print details*/ printf("Enter name: "); gets(pstd->name); printf("Enter roll number: "); scanf("%d",&pstd->roll); printf("Enter percentage: "); scanf("%f",&pstd->perc); printf("nEntered details are:n"); printf("Name: %s, Roll Number: %d, Percentage: %.2fn",pstd->name,pstd- >roll,pstd->perc) return 0; } Output: Enter name: Mike Enter roll number: 1 Enter percentage: 87.50 Entered details are: Name: Mike, Roll Number: 1, Percentage: 87.50
  • 17. C program to read and print the N student details using structure and Dynamic Memory Allocation #include <stdio.h> #include <stdlib.h> struct student { char name[30]; int roll; float perc; }; int main() { struct student *pstd; int n,i; printf("Enter total number of elements: "); scanf("%d",&n); /*Allocate memory dynamically for n objetcs*/ pstd=(struct student*)malloc(n*sizeof(struct student)); if(pstd==NULL) { printf("Insufficient Memory, Exiting... n"); return 0; }
  • 18. /*read and print details*/ for(i=0; i<n; i++) { printf("nEnter detail of student [%3d]:n",i+1); printf("Enter name: "); scanf(" "); /*clear input buffer*/ gets((pstd+i)->name); printf("Enter roll number: "); scanf("%d",&(pstd+i)->roll); printf("Enter percentage: "); scanf("%f",&(pstd+i)->perc); } printf("nEntered details are:n"); for(i=0; i<n; i++) { printf("nEntered details are:n"); for(i=0; i<n; i++) { printf("%30s t %5d t %.2fn",(pstd+i)->name,(pstd+i)- >roll,(pstd+i)->perc); } return 0;}
  • 19. calloc() • The name "calloc" stands for contiguous allocation. • calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. • calloc() takes two arguments: – the number of blocks to be allocated – the size of each block (in bytes) • calloc() returns the address of the chunk of memory that was allocated • calloc() also sets all the values in the allocated memory to zeros • calloc()is also used to dynamically allocate arrays
  • 20. Syntax and Example Syntax: ptr = (castType*)calloc(n, size); Example 1: • ptr = (float*) calloc(25, sizeof(float)); • The above statement allocates contiguous space in memory for 25 elements of type float. Example2: For instance, to dynamically allocate an array of 10 ints: • int*arr; • arr= (int*) calloc(10, sizeof(int)); • /* now arrhas the address • of an array of 10 ints, all 0s */
  • 21. Difference between malloc() and calloc() • malloc() allocates single block of memory whereas leaves the memory uninitialized. • calloc() function allocates multiple blocks of memory of same size and initializes all bits to zero.
  • 22. free() • Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. • You must explicitly use free() to release the space. Syntax of free() free(ptr); • This statement frees the space allocated in the memory pointed by ptr.
  • 23. Program to calculate the sum of n numbers entered by the user using calloc() #include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) calloc(n, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; }
  • 24. Realloc • It is used to dynamically change the memory allocation of a previously allocated memory. • If the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. Syntax: • ptr= realloc(ptr, num_bytes); • where ptr is reallocated with new size 'newSize'. –Find space for new allocation –Copy original data into new space –Free old space –Return pointer to new space
  • 25.
  • 26. Dynamically Allocating 2D Array float **A; /* A is an array (pointer) of float pointers */ int I; A = (float **) calloc(5,sizeof(float *)); /* A is a 1D array (size 5) of float pointers */ for (I = 0; I < 5; I++) A[I] = (float *) calloc(4,sizeof(float)); /* Each element of array points to an array of 4 float variables */ /* A[I][J] is the Jth entry in the array that the Ithmember of A points to */