SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Pointers, References &
Memory Allocation
Gamindu Udayanga
Software Engineer
Metatechno Lanka Company (Pvt) Ltd.
Web : www.metalanka.com
Pointers
 Normal variables contain specific values
 Pointers contains memory addresses of variables
 Variables directly reference values
 Pointers indirectly reference values
 int count = 7;
 int *countPtr = &count;
Declare Pointers & Assign Values
Before C++ 11
int *ptr = NULL; or int *ptr = 0;
C++ 11
int *ptr = nullptr;
Assign value to pointer
int y = 5;
int *ptr = &y;
Dereferencing Pointer
int y = 9;
int *ptr = &y
cout<<y<<endl; //print 9
cout<<ptr<<endl; // print Address of y
cout<<*ptr<<endl; //print 9
*ptr = 10;
cout<<y<<endl;
cout<<ptr<<endl;
cout<<*ptr<<endl;
Pointer Arithmetic
 Appropriate for built in Arrays
 Depend on the size of the object pointer points to
 Pointer arithmetic is Machine ,Environment Defendant
o +
o -
o ++
o --
o +=
o -=
 int v[5] ;
 int *vPtr = v;( Same as int *vPtr = &v[0])
 Built in array name always represents the address of zeroth element of the
Array
Here We assume this machine integer in
4 bytes
 vPtr +=2;//Not adding 2 to the vPtr
 Actual operation is vPtr=3000 +2*4 =>vPtr= 3008
 So vPtr is now pointing to v[2] element;
 ++vPtr; (vPtr = vPtr + 1*4)
 vPtr--;(vPtr = vPtr - 1*4)
 There is no bound checking on pointer arithmetic.
 You must ensure that the results of the pointer arithmetic reference a
element within the built in array’s bound
 Pointer Subtracting
Pointer variables that points to same array can be subtracted;
Pointer Assignment
 A pointer can be assigned to another pointer if both pointers are of same type.
 Otherwise we can use cast opertaors (reinterpret_cast)
double val = 7;
double *ptr = &val;
double *ptr2 = ptr;
void pointer(void *)
 Generic Pointer type that can represent any pointer type
 Any Pointer type to fundamental type or class type can be assigned to void *
without casting
 But void * cannot assigned directly to other pointer types. First we have to
cast void * to proper type
 Void * cannot dereference
 Assigning one pointer type to another type(Other than void *) without casting
is compilation error
 Allowed void pointer operations are comparing ,casting & assigning address to
the void pointer
Pointer Offset Notation(FYI only)
References
 Reference is an alias(another name )for existing variable
 References are introduced in C++(Not use in C)
 Like a pointer reference also stores the address of particular variable
int x = 5;
int &r = x;
Difference between Pointer notation.
int *p = &x;
Difference between a Pointer & a Reference
 Pointer can be reassigned & Reference cannot be reassigned ;
 Reference must be assigned at initialization
 We can assign nullptr to the pointers(NULL or 0 in Before C++ 11 versions).But
we cannot assign nullptr to references
 We cannot do Arithmetic operations on reference directly. There is no such a
thing call reference arithmetic like pointer arithmetic(but you can take the
address of the reference and do pointer arithmetic
Reference to pointers & Pointers to references
 We cannot declare reference to reference or pointer to reference
 We can create reference to any type including pointers
Up to Now, the reference type we discussed is called lvalue
references. There is another type called rvalue references.
 There are two ways of passing values to functions
1)Pass by value
2)Pass by reference(Do not confuse C++ reference type with this reference term)
C++ supports both pass by value and pass by reference semantics. We normally use pass by
reference to achieve two things.
1)Avoid copy overhead
2)Modify original variables
3)Return multiple values
For pass by reference, in C++ we can use two ways
1)pass by pointers
2)pass by reference
When to use what?
Pass by Pointer Example
Pass by reference
Basic Memory Model
Dynamic Memory management in C
 Header File => #include<cstdlib> (#include<stdlib.h in C Language)
 Void *calloc(size_t nmemb, size_t size)
 Void *malloc(size_t size)
 Void free(void *ptr)
 Void *realloc(void *ptr, size_t size)
malloc & free functions
 Void *malloc(size_t size)
Void * calloc(n,sizeof(int)) &
 calloc is same as malloc except it initialize the allocated memory to 0 at the
time of allocating
void realloc(void*ptr,size_t size)
 Size of the dynamically allocated memory can be changed by using realoc
malloc vs new
Dynamic Memory Allocation in C++
 Allocate memory in Heap at runtime(Not compile Time)
When you do not know how much memory will take a
particular object ,It is better to allocate memory at run
time.
 If you allocate memory in heap, you have to solve three problems
1)Freeing memory
2)Handling object copying
3)Handling object assignment
In this session, we mainly focus on freeing memory .Other 2 problems are
discussing in the OOP session.
Dynamic Array
Dynamically Allocated 2d Array
Memory Leaks
 A Memory leaks occurs when programmer allocates memory dynamically and
does not deal locate it when programmer does not need it.
 Memory leaks means memory which is allocated on heap to the program, but
cannot be accessed.
Reassign a pointer
Not Deleting the pointer that goes out of scope
Throw an exception between memory allocation and
deletion
Solution
Dangling Pointer
 A pointer points to an invalid memory location or invalid object.
 An Un initialized non static local pointer variable is a dangling pointer
Solution
Why do we bother when we have smart pointers
 auto_ptr introduced before C++ 11 & deprecated in C++11
 C++11 introduced 3 types of smart pointers
1)shared_ptr
2)weak_ptr
3)unique_ptr
Smart pointers use only for dynamic memory allocation.
Smart pointers can deallocate (free) dynamically allocated memory when the
memory is no longer being used & prevent memory leaks
To use smart pointers we must include memory header.
#include<memory>
Overview of smart pointers
 shared_ptr implements shared ownership.Any number of shared_ptr can
jointly own a object
 weak_ptr does not own a object. weak_ptr observes objects being managed
by shared_ptrs and determine weather the observed object still exist or not
 unique_ptr implements unique ownership.(only one unique pointers owns
the object at a time.When owning smart_pointer is destroyed, then owned
object is automatically destroyed.
 More on shared pointers will be discussed after the OOP sessions.
Remaining Topics
 Exceptions thrown by new operator
 Overload new operator
 Memory Management in Objects
 Writing memory allocator
 Move semantics
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementAnil Bapat
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpprajshreemuthiah
 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
Pointer and polymorphism
Pointer and polymorphismPointer and polymorphism
Pointer and polymorphismSangeethaSasi1
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++Ilio Catallo
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIAjit Nayak
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersRichard Thomson
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1Prerna Sharma
 

Was ist angesagt? (20)

C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
C++ interview question
C++ interview questionC++ interview question
C++ interview question
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
Pointer and polymorphism
Pointer and polymorphismPointer and polymorphism
Pointer and polymorphism
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
structure and union
structure and unionstructure and union
structure and union
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 

Ähnlich wie Pointers Refrences & dynamic memory allocation in C++

Pointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptxPointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptxahmedbadr608094
 
Pointers in C PPT | Poinetrs | Pointers Concept
Pointers in C PPT | Poinetrs | Pointers ConceptPointers in C PPT | Poinetrs | Pointers Concept
Pointers in C PPT | Poinetrs | Pointers Conceptsankalpkumarsahoo174
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfTamiratDejene1
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in Crgnikate
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programmingnmahi96
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptchintuyadav19
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 

Ähnlich wie Pointers Refrences & dynamic memory allocation in C++ (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptxPointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptx
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
Pointers in C PPT | Poinetrs | Pointers Concept
Pointers in C PPT | Poinetrs | Pointers ConceptPointers in C PPT | Poinetrs | Pointers Concept
Pointers in C PPT | Poinetrs | Pointers Concept
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
Types of pointer
Types of pointerTypes of pointer
Types of pointer
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 

Kürzlich hochgeladen (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Pointers Refrences & dynamic memory allocation in C++

  • 1. Pointers, References & Memory Allocation Gamindu Udayanga Software Engineer Metatechno Lanka Company (Pvt) Ltd. Web : www.metalanka.com
  • 2. Pointers  Normal variables contain specific values  Pointers contains memory addresses of variables  Variables directly reference values  Pointers indirectly reference values
  • 3.  int count = 7;  int *countPtr = &count;
  • 4. Declare Pointers & Assign Values Before C++ 11 int *ptr = NULL; or int *ptr = 0; C++ 11 int *ptr = nullptr; Assign value to pointer int y = 5; int *ptr = &y;
  • 5. Dereferencing Pointer int y = 9; int *ptr = &y cout<<y<<endl; //print 9 cout<<ptr<<endl; // print Address of y cout<<*ptr<<endl; //print 9 *ptr = 10; cout<<y<<endl; cout<<ptr<<endl; cout<<*ptr<<endl;
  • 6.
  • 7. Pointer Arithmetic  Appropriate for built in Arrays  Depend on the size of the object pointer points to  Pointer arithmetic is Machine ,Environment Defendant o + o - o ++ o -- o += o -=
  • 8.  int v[5] ;  int *vPtr = v;( Same as int *vPtr = &v[0])  Built in array name always represents the address of zeroth element of the Array
  • 9. Here We assume this machine integer in 4 bytes  vPtr +=2;//Not adding 2 to the vPtr  Actual operation is vPtr=3000 +2*4 =>vPtr= 3008  So vPtr is now pointing to v[2] element;
  • 10.  ++vPtr; (vPtr = vPtr + 1*4)  vPtr--;(vPtr = vPtr - 1*4)  There is no bound checking on pointer arithmetic.  You must ensure that the results of the pointer arithmetic reference a element within the built in array’s bound  Pointer Subtracting Pointer variables that points to same array can be subtracted;
  • 11. Pointer Assignment  A pointer can be assigned to another pointer if both pointers are of same type.  Otherwise we can use cast opertaors (reinterpret_cast) double val = 7; double *ptr = &val; double *ptr2 = ptr;
  • 12. void pointer(void *)  Generic Pointer type that can represent any pointer type  Any Pointer type to fundamental type or class type can be assigned to void * without casting  But void * cannot assigned directly to other pointer types. First we have to cast void * to proper type  Void * cannot dereference  Assigning one pointer type to another type(Other than void *) without casting is compilation error  Allowed void pointer operations are comparing ,casting & assigning address to the void pointer
  • 14. References  Reference is an alias(another name )for existing variable  References are introduced in C++(Not use in C)  Like a pointer reference also stores the address of particular variable int x = 5; int &r = x; Difference between Pointer notation. int *p = &x;
  • 15. Difference between a Pointer & a Reference  Pointer can be reassigned & Reference cannot be reassigned ;  Reference must be assigned at initialization
  • 16.  We can assign nullptr to the pointers(NULL or 0 in Before C++ 11 versions).But we cannot assign nullptr to references  We cannot do Arithmetic operations on reference directly. There is no such a thing call reference arithmetic like pointer arithmetic(but you can take the address of the reference and do pointer arithmetic
  • 17. Reference to pointers & Pointers to references  We cannot declare reference to reference or pointer to reference  We can create reference to any type including pointers
  • 18. Up to Now, the reference type we discussed is called lvalue references. There is another type called rvalue references.  There are two ways of passing values to functions 1)Pass by value 2)Pass by reference(Do not confuse C++ reference type with this reference term) C++ supports both pass by value and pass by reference semantics. We normally use pass by reference to achieve two things. 1)Avoid copy overhead 2)Modify original variables 3)Return multiple values For pass by reference, in C++ we can use two ways 1)pass by pointers 2)pass by reference
  • 19. When to use what?
  • 20. Pass by Pointer Example
  • 23. Dynamic Memory management in C  Header File => #include<cstdlib> (#include<stdlib.h in C Language)  Void *calloc(size_t nmemb, size_t size)  Void *malloc(size_t size)  Void free(void *ptr)  Void *realloc(void *ptr, size_t size)
  • 24. malloc & free functions  Void *malloc(size_t size)
  • 25. Void * calloc(n,sizeof(int)) &  calloc is same as malloc except it initialize the allocated memory to 0 at the time of allocating
  • 26. void realloc(void*ptr,size_t size)  Size of the dynamically allocated memory can be changed by using realoc
  • 28.
  • 29. Dynamic Memory Allocation in C++  Allocate memory in Heap at runtime(Not compile Time)
  • 30. When you do not know how much memory will take a particular object ,It is better to allocate memory at run time.  If you allocate memory in heap, you have to solve three problems 1)Freeing memory 2)Handling object copying 3)Handling object assignment In this session, we mainly focus on freeing memory .Other 2 problems are discussing in the OOP session.
  • 33. Memory Leaks  A Memory leaks occurs when programmer allocates memory dynamically and does not deal locate it when programmer does not need it.  Memory leaks means memory which is allocated on heap to the program, but cannot be accessed. Reassign a pointer
  • 34. Not Deleting the pointer that goes out of scope
  • 35. Throw an exception between memory allocation and deletion
  • 37. Dangling Pointer  A pointer points to an invalid memory location or invalid object.  An Un initialized non static local pointer variable is a dangling pointer
  • 39. Why do we bother when we have smart pointers  auto_ptr introduced before C++ 11 & deprecated in C++11  C++11 introduced 3 types of smart pointers 1)shared_ptr 2)weak_ptr 3)unique_ptr Smart pointers use only for dynamic memory allocation. Smart pointers can deallocate (free) dynamically allocated memory when the memory is no longer being used & prevent memory leaks To use smart pointers we must include memory header. #include<memory>
  • 40. Overview of smart pointers  shared_ptr implements shared ownership.Any number of shared_ptr can jointly own a object  weak_ptr does not own a object. weak_ptr observes objects being managed by shared_ptrs and determine weather the observed object still exist or not  unique_ptr implements unique ownership.(only one unique pointers owns the object at a time.When owning smart_pointer is destroyed, then owned object is automatically destroyed.  More on shared pointers will be discussed after the OOP sessions.
  • 41. Remaining Topics  Exceptions thrown by new operator  Overload new operator  Memory Management in Objects  Writing memory allocator  Move semantics