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

Pointers Refrences & dynamic memory allocation in C++

  • 1.
    Pointers, References & MemoryAllocation Gamindu Udayanga Software Engineer Metatechno Lanka Company (Pvt) Ltd. Web : www.metalanka.com
  • 2.
    Pointers  Normal variablescontain 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;
  • 7.
    Pointer Arithmetic  Appropriatefor 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 assumethis 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  Apointer 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
  • 13.
  • 14.
    References  Reference isan 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 aPointer & a Reference  Pointer can be reassigned & Reference cannot be reassigned ;  Reference must be assigned at initialization
  • 16.
     We canassign 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.
  • 20.
  • 21.
  • 22.
  • 23.
    Dynamic Memory managementin 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 & freefunctions  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
  • 27.
  • 29.
    Dynamic Memory Allocationin C++  Allocate memory in Heap at runtime(Not compile Time)
  • 30.
    When you donot 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.
  • 31.
  • 32.
  • 33.
    Memory Leaks  AMemory 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 thepointer that goes out of scope
  • 35.
    Throw an exceptionbetween memory allocation and deletion
  • 36.
  • 37.
    Dangling Pointer  Apointer points to an invalid memory location or invalid object.  An Un initialized non static local pointer variable is a dangling pointer
  • 38.
  • 39.
    Why do webother 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 smartpointers  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  Exceptionsthrown by new operator  Overload new operator  Memory Management in Objects  Writing memory allocator  Move semantics
  • 42.