SlideShare a Scribd company logo
1 of 29
1
Procedural Concept
• The main program coordinates calls to
procedures and hands over appropriate data
as parameters.
2
Object-Oriented Concept
• Objects of the program interact by sending messages to
each other
3
C++
• Supports Data Abstraction
• Supports OOP
– Encapsulation
– Inheritance
– Polymorphism
• Supports Generic Programming
– Containers
• Stack of char, int, double etc
– Generic Algorithms
• sort(), copy(), search() any container Stack/Vector/List
4
Pointers, Dynamic Data, and
Reference Types
• Review on Pointers
• Reference Variables
• Dynamic Memory Allocation
– The new operator
– The delete operator
– Dynamic Memory Allocation for Arrays
5
C++ Data Types
structured
array struct union class
address
pointer reference
simple
integral enum
char short int long bool
floating
float double long double
6
Recall that . . .
char str [ 8 ];
• str is the base address of the array.
• We say str is a pointer because its value is an address.
• It is a pointer constant because the value of str itself
cannot be changed by assignment. It “points” to the
memory location of a char.
str [0] [1] [2] [3] [4] [5] [6] [7]
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
6000
7
Addresses in Memory
• When a variable is declared, enough memory to hold a value
of that type is allocated for it at an unused memory location.
This is the address of the variable
int x;
float number;
char ch;
2000 2002 2006
x number ch
8
Obtaining Memory Addresses
• The address of a non-array variable can be obtained by using
the address-of operator &
int x;
float number;
char ch;
cout << “Address of x is “ << &x << endl;
cout << “Address of number is “ << &number << endl;
cout << “Address of ch is “ << &ch << endl;
x number ch
2000 2002 2006
9
What is a pointer variable?
• A pointer variable is a variable whose value is the address of a
location in memory.
• To declare a pointer variable, you must specify the type of
value that the pointer will point to, for example,
int* ptr; // ptr will hold the address of an int
char* q; // q will hold the address of a char
10
Using a Pointer Variable
int x;
x = 12;
int* ptr;
ptr = &x;
NOTE: Because ptr holds the address of x,
we say that ptr “points to” x
2000
12
x
3000
2000
ptr
11
int x;
x = 12;
int* ptr;
ptr = &x;
cout << *ptr;
NOTE: The value pointed to by ptr is denoted by *ptr
*: dereference operator
2000
12
x
3000
2000
ptr
12
int x;
x = 12;
int* ptr;
ptr = &x;
*ptr = 5;
Using the Dereference Operator
2000
12
x
3000
2000
ptr
5
// changes the value at the
address ptr points to 5
13
char ch;
ch = ‘A’;
char* q;
q = &ch;
*q = ‘Z’;
char* p;
p = q;
Self –Test on Pointers
4000
A
ch
5000
4000
q
Z
6000
p
4000
// the rhs has value 4000
// now p and q both point to ch
14
ptr
Using a Pointer to Access the
Elements of a String
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
char msg[ ] =“Hello”;
char* ptr;
ptr = msg;
*ptr = ‘M’ ;
ptr++;
*ptr = ‘a’;
msg
3000
3000
‘M’ ‘a’
3001
15
Reference Variables
Reference variable = alias for another variable
- Contains the address of a variable (like a pointer)
- No need to perform any dereferencing (unlike a pointer)
- Must be initialized when it is declared
int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5
z = 9; // same as x = 9;
cout << x << endl; -> prints 9
cout << z << endl; -> prints 9
16
Why Reference Variables
• Are primarily used as function parameters
• Advantages of using references:
– you don’t have to pass the address of a variable
– you don’t have to dereference the variable inside the
called function
17
Reference Variables Example
#include <iostream.h>
// Function prototypes
(required in C++)
void p_swap(int *, int *);
void r_swap(int&, int&);
int main (void){
int v = 5, x = 10;
cout << v << x << endl;
p_swap(&v,&x);
cout << v << x << endl;
r_swap(v,x);
cout << v << x << endl;
return 0;
}
void r_swap(int &a, int &b)
{
int temp;
temp = a; (2)
a = b; (3)
b = temp;
}
void p_swap(int *a, int *b)
{
int temp;
temp = *a; (2)
*a = *b; (3)
*b = temp;
}
18
Dynamic Memory Allocation
• Static memory - where global
and static variables live
• Heap memory - dynamically
allocated at execution time
- "managed" memory accessed
using pointers
• Stack memory - used by
automatic variables
In C and C++, three types of memory are used by programs:
19
3 Kinds of Program Data
• STATIC DATA: Allocated at compiler time
• DYNAMIC DATA: explicitly allocated and
deallocated during program execution by C++
instructions written by programmer using operators
new and delete
• AUTOMATIC DATA: automatically created at
function entry, resides in activation frame of the
function, and is destroyed when returning from
function
20
Dynamic Memory Allocation Diagram
static data
Stack
Heap
Run-time
allocated
memory
Compile-time
allocated
memory
Program
code
High-end
Low-end
21
Dynamic Memory Allocation
• In C, functions such as malloc() are used to
dynamically allocate memory from the Heap.
• In C++, this is accomplished using the new and
delete operators
• new is used to allocate memory during execution time
– returns a pointer to the address where the object is
to be stored
– always returns a pointer to the type that follows the
new
Operator new Syntax
new DataType
new DataType [IntExpression]
• If memory is available, in an area called the heap (or free
store) new allocates the requested object or array, and
returns a pointer to (address of ) the memory allocated.
• Otherwise, program terminates with error message.
• The dynamically allocated object exists until the delete
operator destroys it.
22
23
Operator new
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
NOTE: Dynamic data has no variable name
2000
???
ptr
5000
5000
‘B’
24
The NULL Pointer
• There is a pointer constant called the “null pointer”
denoted by NULL
• But NULL is not memory address 0.
• NOTE: It is an error to dereference a pointer whose
value is NULL. Such an error may cause your
program to crash, or behave erratically. It is the
programmer’s job to check for this.
while (ptr != NULL) {
. . . // ok to use *ptr here
}
Operator delete Syntax
delete Pointer
delete [ ] Pointer
• The object or array currently pointed to by Pointer is
deallocated, and the value of Pointer is undefined. The
memory is returned to the free store.
• Good idea to set the pointer to the released
memory to NULL
• Square brackets are used with delete to deallocate a
dynamically allocated array.
25
26
Operator delete
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
delete ptr;
5000
5000
‘B’
2000
ptr
???
NOTE:
delete deallocates the
memory pointed to by ptr
27
Example
char *ptr ;
ptr = new char[ 5 ];
strcpy( ptr, “Bye” );
ptr[ 0 ] = ‘u’;
delete [] ptr;
ptr = NULL;
‘B’ ‘y’ ‘e’ ‘0’
‘u’
ptr
3000
???
6000
6000
???
NULL
// deallocates the array pointed to by ptr
// ptr itself is not deallocated
// the value of ptr becomes undefined
28
Pointers and Constants
char* p;
p = new char[20];
char c[] = “Hello”;
const char* pc = c; //pointer to a constant
pc[2] = ‘a’; // error
pc = p;
char *const cp = c; //constant pointer
cp[2] = ‘a’;
cp = p; // error
const char *const cpc = c; //constant pointer to a const
cpc[2] = ‘a’; //error
cpc = p; //error
29
Take Home Message
• Be aware of where a pointer points to, and
what is the size of that space.
• Have the same information in mind when
you use reference variables.
• Always check if a pointer points to NULL
before accessing it.

More Related Content

Similar to Lecture2.ppt

Similar to Lecture2.ppt (20)

FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Pointers
PointersPointers
Pointers
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Pointer
PointerPointer
Pointer
 
Chapter16 pointer
Chapter16 pointerChapter16 pointer
Chapter16 pointer
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
Session 5
Session 5Session 5
Session 5
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
Pointers
PointersPointers
Pointers
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
C
CC
C
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Pointer
PointerPointer
Pointer
 
Pointers.pdf
Pointers.pdfPointers.pdf
Pointers.pdf
 
Pointers
PointersPointers
Pointers
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 

Recently uploaded

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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

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...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Lecture2.ppt

  • 1. 1 Procedural Concept • The main program coordinates calls to procedures and hands over appropriate data as parameters.
  • 2. 2 Object-Oriented Concept • Objects of the program interact by sending messages to each other
  • 3. 3 C++ • Supports Data Abstraction • Supports OOP – Encapsulation – Inheritance – Polymorphism • Supports Generic Programming – Containers • Stack of char, int, double etc – Generic Algorithms • sort(), copy(), search() any container Stack/Vector/List
  • 4. 4 Pointers, Dynamic Data, and Reference Types • Review on Pointers • Reference Variables • Dynamic Memory Allocation – The new operator – The delete operator – Dynamic Memory Allocation for Arrays
  • 5. 5 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
  • 6. 6 Recall that . . . char str [ 8 ]; • str is the base address of the array. • We say str is a pointer because its value is an address. • It is a pointer constant because the value of str itself cannot be changed by assignment. It “points” to the memory location of a char. str [0] [1] [2] [3] [4] [5] [6] [7] ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’ 6000
  • 7. 7 Addresses in Memory • When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is the address of the variable int x; float number; char ch; 2000 2002 2006 x number ch
  • 8. 8 Obtaining Memory Addresses • The address of a non-array variable can be obtained by using the address-of operator & int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl; x number ch 2000 2002 2006
  • 9. 9 What is a pointer variable? • A pointer variable is a variable whose value is the address of a location in memory. • To declare a pointer variable, you must specify the type of value that the pointer will point to, for example, int* ptr; // ptr will hold the address of an int char* q; // q will hold the address of a char
  • 10. 10 Using a Pointer Variable int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x 2000 12 x 3000 2000 ptr
  • 11. 11 int x; x = 12; int* ptr; ptr = &x; cout << *ptr; NOTE: The value pointed to by ptr is denoted by *ptr *: dereference operator 2000 12 x 3000 2000 ptr
  • 12. 12 int x; x = 12; int* ptr; ptr = &x; *ptr = 5; Using the Dereference Operator 2000 12 x 3000 2000 ptr 5 // changes the value at the address ptr points to 5
  • 13. 13 char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; Self –Test on Pointers 4000 A ch 5000 4000 q Z 6000 p 4000 // the rhs has value 4000 // now p and q both point to ch
  • 14. 14 ptr Using a Pointer to Access the Elements of a String ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’ char msg[ ] =“Hello”; char* ptr; ptr = msg; *ptr = ‘M’ ; ptr++; *ptr = ‘a’; msg 3000 3000 ‘M’ ‘a’ 3001
  • 15. 15 Reference Variables Reference variable = alias for another variable - Contains the address of a variable (like a pointer) - No need to perform any dereferencing (unlike a pointer) - Must be initialized when it is declared int x = 5; int &z = x; // z is another name for x int &y ; //Error: reference must be initialized cout << x << endl; -> prints 5 cout << z << endl; -> prints 5 z = 9; // same as x = 9; cout << x << endl; -> prints 9 cout << z << endl; -> prints 9
  • 16. 16 Why Reference Variables • Are primarily used as function parameters • Advantages of using references: – you don’t have to pass the address of a variable – you don’t have to dereference the variable inside the called function
  • 17. 17 Reference Variables Example #include <iostream.h> // Function prototypes (required in C++) void p_swap(int *, int *); void r_swap(int&, int&); int main (void){ int v = 5, x = 10; cout << v << x << endl; p_swap(&v,&x); cout << v << x << endl; r_swap(v,x); cout << v << x << endl; return 0; } void r_swap(int &a, int &b) { int temp; temp = a; (2) a = b; (3) b = temp; } void p_swap(int *a, int *b) { int temp; temp = *a; (2) *a = *b; (3) *b = temp; }
  • 18. 18 Dynamic Memory Allocation • Static memory - where global and static variables live • Heap memory - dynamically allocated at execution time - "managed" memory accessed using pointers • Stack memory - used by automatic variables In C and C++, three types of memory are used by programs:
  • 19. 19 3 Kinds of Program Data • STATIC DATA: Allocated at compiler time • DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete • AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function
  • 20. 20 Dynamic Memory Allocation Diagram static data Stack Heap Run-time allocated memory Compile-time allocated memory Program code High-end Low-end
  • 21. 21 Dynamic Memory Allocation • In C, functions such as malloc() are used to dynamically allocate memory from the Heap. • In C++, this is accomplished using the new and delete operators • new is used to allocate memory during execution time – returns a pointer to the address where the object is to be stored – always returns a pointer to the type that follows the new
  • 22. Operator new Syntax new DataType new DataType [IntExpression] • If memory is available, in an area called the heap (or free store) new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. • Otherwise, program terminates with error message. • The dynamically allocated object exists until the delete operator destroys it. 22
  • 23. 23 Operator new char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ??? ptr 5000 5000 ‘B’
  • 24. 24 The NULL Pointer • There is a pointer constant called the “null pointer” denoted by NULL • But NULL is not memory address 0. • NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this. while (ptr != NULL) { . . . // ok to use *ptr here }
  • 25. Operator delete Syntax delete Pointer delete [ ] Pointer • The object or array currently pointed to by Pointer is deallocated, and the value of Pointer is undefined. The memory is returned to the free store. • Good idea to set the pointer to the released memory to NULL • Square brackets are used with delete to deallocate a dynamically allocated array. 25
  • 26. 26 Operator delete char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; 5000 5000 ‘B’ 2000 ptr ??? NOTE: delete deallocates the memory pointed to by ptr
  • 27. 27 Example char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 0 ] = ‘u’; delete [] ptr; ptr = NULL; ‘B’ ‘y’ ‘e’ ‘0’ ‘u’ ptr 3000 ??? 6000 6000 ??? NULL // deallocates the array pointed to by ptr // ptr itself is not deallocated // the value of ptr becomes undefined
  • 28. 28 Pointers and Constants char* p; p = new char[20]; char c[] = “Hello”; const char* pc = c; //pointer to a constant pc[2] = ‘a’; // error pc = p; char *const cp = c; //constant pointer cp[2] = ‘a’; cp = p; // error const char *const cpc = c; //constant pointer to a const cpc[2] = ‘a’; //error cpc = p; //error
  • 29. 29 Take Home Message • Be aware of where a pointer points to, and what is the size of that space. • Have the same information in mind when you use reference variables. • Always check if a pointer points to NULL before accessing it.