SlideShare una empresa de Scribd logo
1 de 20
Memory Management
Dynamic Memory Allocation

• Reserves memory from a much larger free store, or
  heap


• Gives the programmer a pointer to refer to this
  memory
Memory management operators

 There are two types of memory management
 operators in C++:


• new
• delete


 These two memory management operators are
 used for allocating and freeing memory blocks in
 efficient and convenient ways.
New operator


The new operator in C++ is used for dynamic

storage allocation. This operator can be used to

create object of any type.
New operator

The general syntax of new operator in C++ is as
follows:

pointer variable = new datatype;


In the above statement, new is a keyword and the
pointer variable is a variable of type datatype.
New operator

For example:
       int *a=new int;

 The new operator allocates sufficient memory to
 hold the object of datatype int and returns a
 pointer to its starting point. The pointer variable
 a holds the address of memory space allocated.
New operator


Dynamic variables are never initialized by the
compiler. Therefore, the programmer should
make it a practice to first assign them a value.
New operator

The assignment can be made in either of the two
ways:


int *a = new int;
*a = 20;

or

int *a = new int(20);
New operator

Dynamic memory allocation in case of arrays can
be done as following:


int* a = new int[x];


a points to a block of memory
containing x ints
Delete operator


The delete operator in C++ is used for releasing
memory space when the object is no longer
needed. Once a new operator is used, it is
efficient to use the corresponding delete
operator for release of memory.
Delete operator

The general syntax of delete operator in C++ is as
follows:

delete pointer_variable;


In the above example, delete is a keyword and
the pointer_variable is the pointer that points to
the objects already created in the new operator.
Important points while using memory
         management operators

The programmer must take care not to free or
 delete a pointer variable that has already been
 deleted.


Overloading of new and delete operator is
 possible (to be discussed in detail in later section
 on overloading).
Important points while using memory
         management operators

We know that sizeof operator is used for
 computing the size of the object. Using memory
 management operator, the size of the object is
 automatically computed.


The programmer must take care not to free or
 delete pointer variables that have not been
 allocated using a new operator.
Important points while using memory
         management operators

Null pointer is returned by the new operator
 when there is insufficient memory available for
 allocation.
Example:
#include <iostream.h>
  void main()
  {//Allocates using new operator memory space //in
  memory for storing a integer datatype
  int *a= new a;
  *a=100;
  cout << " The Output is:a="<<a;
  //Memory Released using delete operator
  delete a;
 }
Output:

The Output is:a=100
Dynamic Constructor

The constructors can also be used to allocate
memory while creating objects. This will enable
the system to allocate the right amount of memory
for each object when the objects are not of the
same size, thus resulting in the saving of memory.
Allocation of memory to objects at the time of
their construction is known as dynamic
construction of objects. The memory is allocated
with the help of
new operator
# include <iostream.h>
 # include <conio.h>
# include <string.h>
class str
{
char *name;
int len;
public:
str()
{
len=0;
name=new char[len+1];
 }
str(char *s)
void str::join(str &a,str &b)
{
    len=a.len+b.len;
    delete name;
    name=newchar[len+1];
    strcpy(name,a.name);
    strcat(name,b.name);
 };
void main()
 {
   clrscr();
   char *first="HARSHIL";
   str n1(first), n2("NINAD"), n3("PRATIK"), n4, n5;
   n4.join(n1,n2);
   n5.join(n4,n3);
   n1.show();
   n2.show();
   n3.show();
   n4.show();

Más contenido relacionado

La actualidad más candente

Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringSri Harsha Pamu
 
Stack and heap allocation
Stack and heap allocationStack and heap allocation
Stack and heap allocationankitbhasin23
 
decision tree regression
decision tree regressiondecision tree regression
decision tree regressionAkhilesh Joshi
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regressionAkhilesh Joshi
 
On fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLOn fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLSimone Di Maulo
 
Piecewise Functions in Matlab
Piecewise Functions in MatlabPiecewise Functions in Matlab
Piecewise Functions in MatlabJorge Jasso
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmJohn(Qiang) Zhang
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingMandeep Singh
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with SkywritingDerek Murray
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegressionDaniel K
 
Lecture 3.1 to 3.2 bt
Lecture 3.1 to 3.2 btLecture 3.1 to 3.2 bt
Lecture 3.1 to 3.2 btbtmathematics
 
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...hwbloom38
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresJohn(Qiang) Zhang
 

La actualidad más candente (20)

Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
Stack and heap allocation
Stack and heap allocationStack and heap allocation
Stack and heap allocation
 
decision tree regression
decision tree regressiondecision tree regression
decision tree regression
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
 
Lab 1
Lab 1Lab 1
Lab 1
 
On fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLOn fuctional programming, high order functions, ML
On fuctional programming, high order functions, ML
 
Piecewise Functions in Matlab
Piecewise Functions in MatlabPiecewise Functions in Matlab
Piecewise Functions in Matlab
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with Skywriting
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegression
 
Lecture 3.1 to 3.2 bt
Lecture 3.1 to 3.2 btLecture 3.1 to 3.2 bt
Lecture 3.1 to 3.2 bt
 
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
 
hash
 hash hash
hash
 
knn classification
knn classificationknn classification
knn classification
 
Group functions
Group functionsGroup functions
Group functions
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
 
Priority Queue
Priority QueuePriority Queue
Priority Queue
 

Similar a 16829 memory management2

C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onvC++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onvChetanRaut43
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptxAshirwad2
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxhelpme43
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_typesNico Ludwig
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
Devry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newDevry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newwilliamethan912
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Programming II hiding, and .pdf
 Programming II hiding, and .pdf Programming II hiding, and .pdf
Programming II hiding, and .pdfaludin007
 
GLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingGLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingArun Kumar
 
Introduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptxIntroduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptxesuEthopi
 

Similar a 16829 memory management2 (20)

PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
 
memory
memorymemory
memory
 
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onvC++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Pointers
PointersPointers
Pointers
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Pointer
PointerPointer
Pointer
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
Operators
OperatorsOperators
Operators
 
Devry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newDevry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory new
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
Programming II hiding, and .pdf
 Programming II hiding, and .pdf Programming II hiding, and .pdf
Programming II hiding, and .pdf
 
GLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingGLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meeting
 
Introduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptxIntroduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptx
 

Último

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Último (20)

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

16829 memory management2

  • 2. Dynamic Memory Allocation • Reserves memory from a much larger free store, or heap • Gives the programmer a pointer to refer to this memory
  • 3. Memory management operators There are two types of memory management operators in C++: • new • delete These two memory management operators are used for allocating and freeing memory blocks in efficient and convenient ways.
  • 4. New operator The new operator in C++ is used for dynamic storage allocation. This operator can be used to create object of any type.
  • 5. New operator The general syntax of new operator in C++ is as follows: pointer variable = new datatype; In the above statement, new is a keyword and the pointer variable is a variable of type datatype.
  • 6. New operator For example: int *a=new int; The new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated.
  • 7. New operator Dynamic variables are never initialized by the compiler. Therefore, the programmer should make it a practice to first assign them a value.
  • 8. New operator The assignment can be made in either of the two ways: int *a = new int; *a = 20; or int *a = new int(20);
  • 9. New operator Dynamic memory allocation in case of arrays can be done as following: int* a = new int[x]; a points to a block of memory containing x ints
  • 10. Delete operator The delete operator in C++ is used for releasing memory space when the object is no longer needed. Once a new operator is used, it is efficient to use the corresponding delete operator for release of memory.
  • 11. Delete operator The general syntax of delete operator in C++ is as follows: delete pointer_variable; In the above example, delete is a keyword and the pointer_variable is the pointer that points to the objects already created in the new operator.
  • 12. Important points while using memory management operators The programmer must take care not to free or delete a pointer variable that has already been deleted. Overloading of new and delete operator is possible (to be discussed in detail in later section on overloading).
  • 13. Important points while using memory management operators We know that sizeof operator is used for computing the size of the object. Using memory management operator, the size of the object is automatically computed. The programmer must take care not to free or delete pointer variables that have not been allocated using a new operator.
  • 14. Important points while using memory management operators Null pointer is returned by the new operator when there is insufficient memory available for allocation.
  • 15. Example: #include <iostream.h> void main() {//Allocates using new operator memory space //in memory for storing a integer datatype int *a= new a; *a=100; cout << " The Output is:a="<<a; //Memory Released using delete operator delete a; }
  • 17. Dynamic Constructor The constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus resulting in the saving of memory. Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The memory is allocated with the help of new operator
  • 18. # include <iostream.h> # include <conio.h> # include <string.h> class str { char *name; int len; public: str() { len=0; name=new char[len+1]; } str(char *s)
  • 19. void str::join(str &a,str &b) { len=a.len+b.len; delete name; name=newchar[len+1]; strcpy(name,a.name); strcat(name,b.name); };
  • 20. void main() { clrscr(); char *first="HARSHIL"; str n1(first), n2("NINAD"), n3("PRATIK"), n4, n5; n4.join(n1,n2); n5.join(n4,n3); n1.show(); n2.show(); n3.show(); n4.show();