SlideShare a Scribd company logo
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.
Most read
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.
Most read
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.
Most read
Dynamic memory allocation in c++
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.

More Related Content

What's hot (20)

Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
Neeru Mittal
 
This pointer
This pointerThis pointer
This pointer
Kamal Acharya
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
Jsaddam Hussain
 

Similar to Dynamic memory allocation in c++ (20)

C++tutorial
C++tutorialC++tutorial
C++tutorial
dips17
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Linked list
Linked listLinked list
Linked list
somuinfo123
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
Abhishekkumarsingh630054
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
RAJ KUMAR
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
HimanshuSharma997566
 
Memory Management for C and C++ _ language
Memory Management for C and C++ _ languageMemory Management for C and C++ _ language
Memory Management for C and C++ _ language
23ecuos117
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
Sabaunnisa3
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
ShriKant Vashishtha
 
(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
Nico Ludwig
 
Pointer
PointerPointer
Pointer
manish840
 
CLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.pptCLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.ppt
NikeshaPatel1
 
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptxUnit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
TriggeredZulkar
 
data structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptxdata structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptx
sandeepg77
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
ngonidzashemutsipa
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
ngonidzashemutsipa
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
dips17
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
RAJ KUMAR
 
Memory Management for C and C++ _ language
Memory Management for C and C++ _ languageMemory Management for C and C++ _ language
Memory Management for C and C++ _ language
23ecuos117
 
(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
Nico Ludwig
 
CLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.pptCLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.ppt
NikeshaPatel1
 
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptxUnit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
TriggeredZulkar
 
data structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptxdata structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptx
sandeepg77
 
Ad

More from Tech_MX (20)

Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Uid
UidUid
Uid
Tech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
Tech_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 application
Tech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_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
 
Spss
SpssSpss
Spss
Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
Tech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
Tech_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 System
Tech_MX
 
Parsing
ParsingParsing
Parsing
Tech_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 pc
Tech_MX
 
More on Lex
More on LexMore on Lex
More on Lex
Tech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
Tech_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 dbms
Tech_MX
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
Tech_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 application
Tech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_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 & applications
Tech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
Tech_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 System
Tech_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 pc
Tech_MX
 
More on Lex
More on LexMore on Lex
More on Lex
Tech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
Tech_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 dbms
Tech_MX
 
Ad

Recently uploaded (20)

AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 

Dynamic memory allocation in c++

  • 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.