0% found this document useful (0 votes)
23 views36 pages

Pointers

The document provides an overview of C++ data types, focusing on pointers and memory management. It covers topics such as pointer declaration, dereferencing, dynamic memory allocation, and the implications of dangling pointers and memory leaks. Key operations and examples illustrate how to effectively use pointers in C++ programming.

Uploaded by

abubakar01901
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views36 pages

Pointers

The document provides an overview of C++ data types, focusing on pointers and memory management. It covers topics such as pointer declaration, dereferencing, dynamic memory allocation, and the implications of dangling pointers and memory leaks. Key operations and examples illustrate how to effectively use pointers in C++ programming.

Uploaded by

abubakar01901
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

C++ Data Types

simple structured

integral enum floating array struct union class

char short int long bool


address

float double long double


pointer reference

1
Topics
• Using the Address-Of Operator &
• Declaring and Using Pointer Variables
• Using the Indirection (Dereference) Operator *
• The NULL Pointer
• Using C++ Operators new and delete
• Meaning of an Inaccessible Object
• Meaning of a Dangling Pointer

2
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.
6000

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

str [0] [1] [2] [3] [4] [5] [6] [7]

3
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
4
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;

5
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 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

6
Using a Pointer Variable
2000
int x;
12
x = 12;
x

int* ptr; 3000


ptr = &x;
2000
ptr

NOTE: Because ptr holds the address of x,


we say that ptr “points to” x

7
Unary operator * is the indirection
(dereference) operator
2000

int x; 12
x = 12; x

3000
int* ptr;
2000
ptr = &x;
ptr
cout << *ptr;

NOTE: The value pointed to by ptr is denoted by *ptr

8
Using the Dereference Operator

2000
int x;
12 5
x = 12;
x

int* ptr; 3000


ptr = &x; 2000
ptr
*ptr = 5; // Changes the value
// at address ptr to 5

9
Another Example
char ch; 4000

ch = ‘A’; A Z
ch
char* q;
5000 6000
q = &ch;
4000 4000
*q = ‘Z’; q p
char* p;
p = q; // The rhs has value 4000
// Now p and q both point to ch

10
Using a Pointer to Access the Elements of a String
3000
char msg[ ]=“Hello”; ‘M’ ‘a’
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

3001
char* ptr; 3000

ptr

ptr = msg; // Recall that msg ==


// &msg[ 0 ]
*ptr = ‘M’;
ptr++; // Increments the address
*ptr = ‘a’; // in ptr
11
int StringLength (/* in */ const char str[ ])
// Precondition: str is a null-terminated string
// Postcondition: Return value == length of str
// (not counting ‘\0’)
{
char* p;
int count = 0;
p = str;
while (*p != ‘\0’)
{
count++;
p++;
// Increments the address p by sizeof char
}
return count;

12
12
Some C++ Pointer Operations
Precedence
Higher -> Select member of class pointed to

Unary: ++ -- ! * new delete


Increment, Decrement, NOT, Dereference, Allocate, Deallocate

Binary: + - Add Subtract

< <= > >= Relational operators

== != Tests for equality, inequality

Lower = Assignment
13
Operator new Syntax
new DataType

new DataType [IntExpression]

If memory is available in an area called the heap (or free


store) new allocates space for 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

14
The NULL Pointer

NULL is a pointer constant 0, defined in header file cstddef,


that means that the pointer points to nothing
• It is an error to dereference a pointer whose value is NULL
• Such an error may cause your program to crash, or
behave erratically
while (ptr != NULL)
{
. . . // Ok to use *ptr here
}

15
3 Kinds of Program Data
• Static data: memory allocation exists throughout
execution of program
static long currentSeed;

• Automatic data: automatically created at function entry,


resides in activation frame of the function, and is
destroyed when returning from function
• Dynamic data: explicitly allocated and deallocated during
program execution by C++ instructions written by
programmer using operators new and delete

16
Allocation of Memory

STATIC DYNAMIC
ALLOCATION ALLOCATION

Static allocation is Dynamic allocation is


the allocation of the allocation of
memory space at memory space at run
compile time time by using
operator new

17
Dynamically Allocated Data
2000
char* ptr;

ptr
ptr = new char;
*ptr = ‘B’;
cout << *ptr;

18
Dynamically Allocated Data
char* ptr; 2000

ptr = new char; ptr


*ptr = ‘B’;
cout << *ptr;

NOTE: Dynamic data has no variable name

19
Dynamically Allocated Data
char* ptr; 2000

ptr = new char;


*ptr = ‘B’; ptr
cout << *ptr;
‘B’

NOTE: Dynamic data has no variable name

20
Dynamically Allocated Data
2000
char* ptr;
?

ptr = new char; ptr


*ptr = ‘B’;
cout << *ptr;
delete ptr; NOTE: delete deallocates the
memory pointed to by ptr

21
Memory Allocation

22
Using Operator delete

• Operator delete returns memory to the free store,


which was previously allocated at run-time by operator
new

• The object or array currently pointed to by the pointer is


deallocated, and the pointer is considered unassigned

23
Dynamic Array Allocation
char *ptr;// ptr is a pointer variable that
// can hold the address of a char
ptr = new char[ 5 ];
// Allocates memory for a 5-character array // dynamically
at run time and stores the
// base address into ptr

6000

6000

ptr
24
Dynamic Array Allocation
char *ptr;

ptr = new char[ 5 ];

strcpy(ptr, “Bye”);

ptr[ 1 ] = ‘u’;
// A pointer can be subscripted
cout << ptr[ 2];

6000
‘u’
6000 ‘B’ ‘y’ ‘e’ ‘\0’
ptr
25
Dynamic Arrays

26
Operator delete Syntax
delete Pointer

delete [ ] Pointer

If the value of the pointer is NULL there is no effect


Otherwise, 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
Square brackets are used with delete to deallocate a
dynamically allocated array
27
Dynamic Array Deallocation
char *ptr;

ptr = new char[ 5 ];


strcpy(ptr, “Bye”);
ptr[ 1 ] = ‘u’;
delete ptr;
// Deallocates array pointed to by ptr
// ptr itself is not deallocated
// The value of ptr is undefined

ptr
28
What happens here?

int* ptr = new int;


3
*ptr = 3;
ptr

ptr = new int; // Changes value of ptr


*ptr = 4;
3

ptr

29
Inaccessible Object

An inaccessible object is an unnamed object created by


operator new that a programmer has left without a
pointer to it.

int* ptr = new int; 8

*ptr = 8; ptr
int* ptr2 = new int;
-5
*ptr2 = -5;
ptr2

30
Making an Object Inaccessible

int* ptr = new int; 8


*ptr = 8; ptr
int* ptr2 = new int;
-5
*ptr2 = -5;
ptr2

ptr = ptr2;
//Here the 8 becomes
8
// inaccessible
ptr

-5

ptr2
31
Memory Leak

A memory leak is the loss of available memory space


that occurs when dynamic data is allocated but
never deallocated

32
A Dangling Pointer

• A dangling pointer is a pointer that points to dynamic


memory that has been deallocated

int* ptr = new int;


*ptr = 8; 8

int* ptr2 = new int; ptr


*ptr2 = -5; -5
ptr = ptr2;
ptr2

For example,
33
Leaving a Dangling Pointer

int* ptr = new int; 8


*ptr = 8; ptr
int* ptr2 = new int;
-5
*ptr2 = -5;
ptr = ptr2; ptr2

8
delete ptr2;
// ptr is left dangling ptr
ptr2 = NULL; NULL
ptr2
34
Dangling Pointer
• int *myPointer;
• myPointer=new int(10);
• cout <<“The value of myPointer is “<<*myPointer<<endl;
• delete myPointer;
• *myPointer=5;
• Cout<<“The value of myPointer is “ <<*myPointer<<endl;

35
Dangling Pointer
• Corrected Code:

• myPointer=new int(10);
• cout <<“The value of myPointer is “<<*myPointer<<endl;
• delete myPointer;
• myPointer=0;
• *myPointer=5;// This will cause a runt-time exception now
• Cout<<“The value of myPointer is “ <<*myPointer<<endl;

36

You might also like