SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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++
 

Similar to Pointers, References & Memory Allocation in C/C++ (Under 40 chars

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
 

Similar to Pointers, References & Memory Allocation in C/C++ (Under 40 chars (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
 

Recently uploaded

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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Recently uploaded (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
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

Pointers, References & Memory Allocation in C/C++ (Under 40 chars

  • 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