SlideShare a Scribd company logo
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++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
Kaushik Raghupathi
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Anil Bapat
 
C++ interview question
C++ interview questionC++ interview question
C++ interview question
Durgesh Tripathi
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
C interview questions
C interview questionsC interview questions
C interview questions
Soba Arjun
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
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 5th
Connex
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
Emertxe Information Technologies Pvt Ltd
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
Pointer and polymorphism
Pointer and polymorphismPointer and polymorphism
Pointer and polymorphism
SangeethaSasi1
 
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 III
Ajit Nayak
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
Dushmanta Nath
 
structure and union
structure and unionstructure and union
structure and union
student
 
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
Richard Thomson
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
Prerna Sharma
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
Docent Education
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
Francesco Casalegno
 

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 Refrences & dynamic memory allocation in C++

Pointers in C
Pointers in CPointers in C
Pointers in C
Vijayananda Ratnam Ch
 
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
ahmedbadr608094
 
C programming session8
C programming  session8C programming  session8
C programming session8
Keroles karam khalil
 
C programming session8
C programming  session8C programming  session8
C programming session8
Keroles karam khalil
 
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
sankalpkumarsahoo174
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
Types of pointer
Types of pointerTypes of pointer
Types of pointer
Ravindra Nikate
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
rgnikate
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Mufaddal Nullwala
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
Koganti Ravikumar
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
tech4us
 
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
Rai University
 
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
Rai 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 handling
Rai 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 handling
Rai 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 handling
Rai University
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 
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
Rai University
 

Similar to 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)
 
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
 
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
 
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

GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 

Recently uploaded (20)

GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 

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