SlideShare ist ein Scribd-Unternehmen logo
1 von 16
PROBLEMS WITH NORMAL ARRAY
           VARIABLE DECLARATION

Int main()         // 1 . Size fixed
{
                       1020       1022     1024      1026      1028
Int A[5];              A[0]       A[1]     A[2]         A[3]   A[4]


Int B[n];          // 2. Error..Size must be known at
                   compile time.
}
Will not work for larger programs because of the limited size of the
stack.
HEAP AND STACK
   Our program when loaded in to main memory is divided in to 4
    segments : CODE,DATA,STACK,HEAP

   A data segment contains the global variables and static variables.

   A code(text) segment contains the executable instructions.

   A Stack segment store all the auto variables. Also each function call
    involves passing arguments from the caller to the callee. The callee
    may also declare variables. Function parameters ,return address
    and automatic local variables are accommodated in the stack.
   Hence a stack is an area of memory for storing data temporarily.
 Allocation and de allocation of memory in this area is done
  automatically .
 Heap segment is for dynamic memory management.
 It is for the programmers to manage.
 We can allocate memory when you feel the need for it and delete
  when you feel that the memory is no longer needed
 And it is the responsibility of the programmer to delete memory
  when no longer needed.
 Hence for array we can dynamically allocate memory of size which
   can be determined at run time.
 C programs use a pair of functions named malloc and free to
   allocate space from the heap.
 In C++ we use new and delete.
DEFINING A DYNAMIC ARRAY
   When we define an array variable, we specify a type , a name, and a
    dimension.
                            int a[2]
   When we dynamically allocate an array, we specify the type and size
    but no name

   This new expression allocates an array of ten integers and returns a
    pointer to the first element in that array, which we use to initialize ptr.
                         int *ptr = new int[10];
        // array of 10 uninitialized integers (contain garbage value)

   Objects allocated on the free store are unnamed. We use objects on
    the heap only indirectly through their address.
   To value initialise the array we can use empty parentheses in the
    expression.

              int *pia2 = new int[10] (); // initialized to 0

   This effectively send a request to the compiler to value-initialize the
    array, which in this case sets its elements to 0.
   The elements of a dynamically allocated array can be initialized only to
    the default value of the element type.
    The elements cannot be initialized to separate values as can be done
    for elements of an array variable.

                    int a[2]={1,2};
   int* nums2 = new int[x];                 // ok
     Value of x is obtained during run time and even the memory
    allocation is done dynamically

   For multidimensional arrays
        int x = 3, y = 4;
       int* nums3 = new int[x][4][5];      // ok
       int* nums4 = new int[x][y][5];      // BAD!

   Only the first dimension can be a variable. The rest must be
    constants.
DEALLOCATING MEMORY
 When we allocate memory, we must eventually free it.
 Otherwise, memory is gradually used up and may be exhausted
 We do so by applying the delete [] expression to a pointer that
  addresses the array we want to release:
          delete [ ] ptr; //de allocates the array pointed to by ptr
 The empty bracket pair between the delete keyword and the pointer is
  necessary
 It indicates to the compiler that the pointer addresses an array of
  elements
 It is essential to remember the bracket-pair when deleting pointers to
  arrays.
 For every call to new, there must be exactly one call to delete.
MALLOC AND FREE
   Memory allocation can be done using malloc as:
         int* nums = (int*)malloc(5*sizeof(int));
    This is similar to int *nums = new int[5];
    De allocation can be done using free as
        free(nums)
    This is similar to delete[ ] nums.
   C++ also supports malloc and free as we know that C++ is a
    superset of C.
WHY NEW IF MALLOC ?
 With simple variables and arrays new and delete does the same
  functionality as malloc and free respectively.
 But the scenario changes when we need to work with the classes
  where we use constructors to assign values to the data members.
 As with classes new allocates space to hold the object which are the
  instance of the class.
 new calls the object’s default constructor.
   Example : for a given class ‘cls’ ,

    cls *ptr = new cls;   // calls default constructor of cls. If not found
                            , automatically compiler generated
                            constructor is called
   cls *ptr = new cls(2); // calls one parameterized constructor of cls.
    If not found , throws error

   new returns a pointer to the object of the class.

   Though malloc does allocate memory for the given type it cannot call
    the constructor which are the special member functions that are used
    to assign values to variables.

   new is an operator, while malloc() is a function.

   new returns exact data type, while malloc() returns void pointer
EXAMPLE:

#include<iostream>                   void disp()
Using namespace std;                 { cout<<"na:"<<a; }
class cls {                          };
   int a;                            void main()
   public:                           {
 cls() {                             clrscr();
   a=5;                              cls *ptr = new cls;
   cout<<"nConstructor called"; }   ptr->disp();
~cls()                               delete ptr;
{ cout<<"nDestructor called"; }     getch();
                                     }
OUTPUT:


          Constructor called
          a=5
          Destructor called
EXAMPLE:

#include<iostream>                   void disp()
Using namespace std;                 { cout<<"na:"<<a; }
class cls {                          };
   int a;                            void main()
   public:                           {
 cls() {                             clrscr();
   a=5;                              cls *ptr = (cls*)malloc(sizeof(cls))
   cout<<"nConstructor called"; }   ptr->disp();
~cls()                               free(ptr);
{ cout<<"nDestructor called"; }     getch();
                                     }
OUTPUT:


                         a=56378

 // Garbage value
 // Didn’t call neither the constructor nor the destructor
CAUTION: MANAGING DYNAMIC
    MEMORY IS ERROR-PRONE
Some common program errors are associated with dynamic
memory allocation:
 Failing to delete a pointer to dynamically allocated
  memory, thus preventing the memory from being returned to
  the free store. Failure to delete dynamically allocated memory
  is spoken of as a "memory leak.”
 Applying a delete expression to the same memory location
  twice. This error can happen when two pointers address the
  same dynamically allocated object. If delete is applied to one
  of the pointers, then the object's memory is returned to the
  free store. If we subsequently delete the second pointer, then
  the free store may be corrupted.

Weitere ähnliche Inhalte

Was ist angesagt?

Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in javaHrithikShinde
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programmingKamal Acharya
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaHitesh Kumar
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++Sujan Mia
 

Was ist angesagt? (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
STL in C++
STL in C++STL in C++
STL in C++
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
Java package
Java packageJava package
Java package
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Applets
AppletsApplets
Applets
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 

Ähnlich wie Dynamic memory allocation in c++

Ähnlich wie Dynamic memory allocation in c++ (20)

C++tutorial
C++tutorialC++tutorial
C++tutorial
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Link list
Link listLink list
Link list
 
Linked list
Linked listLinked list
Linked list
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 
Pointer
PointerPointer
Pointer
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
 
cp05.pptx
cp05.pptxcp05.pptx
cp05.pptx
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 

Mehr von Tech_MX

Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimationTech_MX
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
String & its application
String & its applicationString & its application
String & its applicationTech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating SystemTech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pcTech_MX
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbmsTech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbmsTech_MX
 

Mehr von Tech_MX (20)

Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Uid
UidUid
Uid
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Spss
SpssSpss
Spss
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Set data structure
Set data structure Set data structure
Set data structure
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
More on Lex
More on LexMore on Lex
More on Lex
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 

Kürzlich hochgeladen

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Dynamic memory allocation in c++

  • 1.
  • 2. PROBLEMS WITH NORMAL ARRAY VARIABLE DECLARATION Int main() // 1 . Size fixed { 1020 1022 1024 1026 1028 Int A[5]; A[0] A[1] A[2] A[3] A[4] Int B[n]; // 2. Error..Size must be known at compile time. } Will not work for larger programs because of the limited size of the stack.
  • 3. HEAP AND STACK  Our program when loaded in to main memory is divided in to 4 segments : CODE,DATA,STACK,HEAP  A data segment contains the global variables and static variables.  A code(text) segment contains the executable instructions.  A Stack segment store all the auto variables. Also each function call involves passing arguments from the caller to the callee. The callee may also declare variables. Function parameters ,return address and automatic local variables are accommodated in the stack.  Hence a stack is an area of memory for storing data temporarily.
  • 4.  Allocation and de allocation of memory in this area is done automatically .  Heap segment is for dynamic memory management.  It is for the programmers to manage.  We can allocate memory when you feel the need for it and delete when you feel that the memory is no longer needed  And it is the responsibility of the programmer to delete memory when no longer needed.  Hence for array we can dynamically allocate memory of size which can be determined at run time.  C programs use a pair of functions named malloc and free to allocate space from the heap.  In C++ we use new and delete.
  • 5. DEFINING A DYNAMIC ARRAY  When we define an array variable, we specify a type , a name, and a dimension. int a[2]  When we dynamically allocate an array, we specify the type and size but no name  This new expression allocates an array of ten integers and returns a pointer to the first element in that array, which we use to initialize ptr. int *ptr = new int[10]; // array of 10 uninitialized integers (contain garbage value)  Objects allocated on the free store are unnamed. We use objects on the heap only indirectly through their address.
  • 6. To value initialise the array we can use empty parentheses in the expression. int *pia2 = new int[10] (); // initialized to 0  This effectively send a request to the compiler to value-initialize the array, which in this case sets its elements to 0.  The elements of a dynamically allocated array can be initialized only to the default value of the element type.  The elements cannot be initialized to separate values as can be done for elements of an array variable. int a[2]={1,2};
  • 7. int* nums2 = new int[x]; // ok Value of x is obtained during run time and even the memory allocation is done dynamically  For multidimensional arrays int x = 3, y = 4; int* nums3 = new int[x][4][5]; // ok int* nums4 = new int[x][y][5]; // BAD!  Only the first dimension can be a variable. The rest must be constants.
  • 8. DEALLOCATING MEMORY  When we allocate memory, we must eventually free it.  Otherwise, memory is gradually used up and may be exhausted  We do so by applying the delete [] expression to a pointer that addresses the array we want to release: delete [ ] ptr; //de allocates the array pointed to by ptr  The empty bracket pair between the delete keyword and the pointer is necessary  It indicates to the compiler that the pointer addresses an array of elements  It is essential to remember the bracket-pair when deleting pointers to arrays.  For every call to new, there must be exactly one call to delete.
  • 9. MALLOC AND FREE  Memory allocation can be done using malloc as: int* nums = (int*)malloc(5*sizeof(int)); This is similar to int *nums = new int[5];  De allocation can be done using free as free(nums) This is similar to delete[ ] nums.  C++ also supports malloc and free as we know that C++ is a superset of C.
  • 10. WHY NEW IF MALLOC ?  With simple variables and arrays new and delete does the same functionality as malloc and free respectively.  But the scenario changes when we need to work with the classes where we use constructors to assign values to the data members.  As with classes new allocates space to hold the object which are the instance of the class.  new calls the object’s default constructor. Example : for a given class ‘cls’ , cls *ptr = new cls; // calls default constructor of cls. If not found , automatically compiler generated constructor is called
  • 11. cls *ptr = new cls(2); // calls one parameterized constructor of cls. If not found , throws error  new returns a pointer to the object of the class.  Though malloc does allocate memory for the given type it cannot call the constructor which are the special member functions that are used to assign values to variables.  new is an operator, while malloc() is a function.  new returns exact data type, while malloc() returns void pointer
  • 12. EXAMPLE: #include<iostream> void disp() Using namespace std; { cout<<"na:"<<a; } class cls { }; int a; void main() public: { cls() { clrscr(); a=5; cls *ptr = new cls; cout<<"nConstructor called"; } ptr->disp(); ~cls() delete ptr; { cout<<"nDestructor called"; } getch(); }
  • 13. OUTPUT: Constructor called a=5 Destructor called
  • 14. EXAMPLE: #include<iostream> void disp() Using namespace std; { cout<<"na:"<<a; } class cls { }; int a; void main() public: { cls() { clrscr(); a=5; cls *ptr = (cls*)malloc(sizeof(cls)) cout<<"nConstructor called"; } ptr->disp(); ~cls() free(ptr); { cout<<"nDestructor called"; } getch(); }
  • 15. OUTPUT: a=56378 // Garbage value // Didn’t call neither the constructor nor the destructor
  • 16. CAUTION: MANAGING DYNAMIC MEMORY IS ERROR-PRONE Some common program errors are associated with dynamic memory allocation:  Failing to delete a pointer to dynamically allocated memory, thus preventing the memory from being returned to the free store. Failure to delete dynamically allocated memory is spoken of as a "memory leak.”  Applying a delete expression to the same memory location twice. This error can happen when two pointers address the same dynamically allocated object. If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.