Sei sulla pagina 1di 31

POINTERS, POINTERS & MORE

POINTERS
CS 201 Data structures & algorithms
Mehreen Saeed

Taken mostly from:


Data structures and algorithms by
Adam Drozdek,
pointers and memory by Nick
Parlante
(http://cslibrary.stanford.edu/)
Say no to bugs!
Slid No. 1

DIFFERENCE BETWEEN POINTERS & VARIABLES

Variables :

Content
Location
X

Location is the variable name from


the point of view of a programmer
10
Address of a
memory slot

Pointers : The content is


location of another variable

Allow us to access value of other


variables indirectly

int X = 10;
int *P;
P = &X;

P
P

&X

Location

X
10

Slid No. 2

BENEFITS OF USING PTRS


Pointers allow different chunks of
memory to be shared by different
sections of code
So we dont need to make several copies of
the same data for different portions of code
but use a pointer to access the same data

Required for building useful data


structures like linked lists and binary
trees, etc.
Slid No. 3

SOME IMPORTANT TERMS RELATED TO PTRS


REFERENCE & DEREFERENCE

A pointer stores the address of a memory


location.we say it stores a REFERENCE to
another value
DEREFERENCE operationmeans we want to
get the value of the contents of the memory
location that a pointer is pointing to
1.int *p;
2.int x = 10;
3.p = &x; //(address operator). p stores
reference to x
4.cout << *p ; (* is the de-reference operator)
(what will be printed here????)

Slid No. 4

SOME IMPORTANT TERMS RELATED TO PTRS (contd)


NULL POINTER

NULL pointer means pointer is pointing


to nothing,symbol:
In C++ NULL is a constant for value zero
So int *p = 0 is the same as int *p = NULL

Always initialize a pointer to


NULL value after declaring it

Slid No. 5

NULL vs. nullptr

int *x;
x = 0;
x = NULL;
x = nullptr

all 3
statements
are equivalent

void f1(int *x){ //do something}


void f1(int x) { //do something}
void caller()
{
f1(0);
//which version of f1 is called
f1(NULL); //which version of f1 is called
f1(nullptr); //which version
int *x=NULL;
f1(x);
//which version of f1 is called
int *x = nullptr;
f1(x);
//which version of f1 is called
}

Slid No. 6
NULL is a CONSTANT for number ZERO and nullptr is a pointer TYPE

MEMORY ALLOCATION
Dynamic allocation : Allocation of memory
or space for a variable at run time.
Static allocation : Allocation is done
before the program starts
Heap : A region of memory set aside for
dynamic allocation. Also called free
store. Variables created by new
operator are said to be on the heap / free
store

Slid No. 7

VARIABLES & PTRS AGAIN.LIFETIME


Local variable is allocated when a function is
called and de-allocated when a function exits.
Local variables are also called automatic as they
are automatically allocated/deallocated
Local variables are also called stack variables as
most languages allocate them on the system
stack when a function is called

When a memory is allocated using new


operatorthe memory is allocated for the entire
lifetime of a program or until the delete
operator is called
We can control the size of memory
We have to do more work
We might end up with more bugs if we are not careful
Slid No. 8

Example 1 : Pointing to a variable


int a,*p
a=10;

10

p=&a //no memory is allocated


*p becomes invalid as soon as a is deallocated

Example 2 :

10
Int a,*p
a=10;
p=new int //new memory is allocated at runtime
Slid No. 9
This is new space created

From Adam Drozdek

Slid No. 10

A COMMON BUG

int *p;
*p = 20;

The code looks quite harmless.what


is wrong with it????

p should have been


allocated memory or
assigned a legal reference

Slid No. 11

MEMORY LEAKS
int *x = NULL,*p = NULL;
x = new int;
p = new int;
*x = 10;

10

*p = 12;

12
p

10

p = x;
What happens to
this location ???

It cannot be accessed
Cannot be used again
Creates a Memory leak
The memory that can no longer be accessed is called GARBAGE

Slid No. 12

DANGLING POINTER
int *x = NULL,*p = NULL;
x = new int;
p = new int;
*x = 10;

10

*p = 12;

12

p = x;

10

delete p

WHAT HAPPENS NOW????

*x = 15
Not only do we
have a memory
leak BUT also a
dangling pointer x

this is given
back to
system

p
10

THIS WILL
CRASH
Slid No. 13

POINTERS

Not again!!!

Declaration:
Type of

int **p

Total number of stars is the


same

p: int ***
*

Type of

*p:int *

Type of

**p:int

Type of

&p:int***
Slid No. 14

STUDY THIS CODE


void Increment(int *x)
{
*x = *x+1
}

If we want to change the


value of a we have to
pass the address of a

void CallIncrement()
{
int a=10;
Increment(&a);
}
Increment
CallIncrement

x
a

x and a are two different


variables
x has the address of a

Slid No. 15

So generalizing
void ChangePointer(int **p)
{
*p = new int;
**p = 10;
}
void CallChangePointer()
{
int *a = NULL;
ChangePointer(&a)
}

ChangePointer
CallChangePointer

If we want to change a we
have to pass the address of a

p
a
10

p has the address of a


which can now be
changed by
ChangePointer
allocated by new

Slid No. 16

Why would this code crash????

void ChangePointer(int *p)


{
p = new int;
*p = 10;
}
void CallChangePointer()
{
int *a = NULL;
ChangePointer(a);
*a = 1;
}

There are two major


problemsidentify them

Slid No. 17

and some more generalizing


void ChangePointer(int **p)
{
*p = new int;
**p = 10;
}
void Increment(int *x)
{
*x=*x+1;
}
void CallChangePointer()
{
int *a = NULL;
ChangePointer(&a);
Increment(a)
}
Increment
CallChangePointer

Notice that we can simply


pass a if we want to change
the value of *a. The function
increment does that

to change the value


pointed to by a we can
simply pass a and not
the address of a

x
a
11

allocated by new

Slid No. 18

VERY COMMON BUGEXAMPLE OF


DANGLING POINTER
What is wrong
int *GetPtr()
here???
{
int a=0;
a was allocated
return &a;
when GetPtr called
and deallocated
}
when GetPtr exited
void main()
a memory location
{
no longer exists
int *p = GetPtr();
*p = 10;
Here we are accessing
a memory location
}
that no longer exists
Dangling pointers are pointers that do not point to valid objects in
Slid No. 19
memory like this one

VERY COMMON BUGEXAMPLE OF DANGLING


POINTER (contd)
int *GetPtr()
Write the correct
{
version here
int a=0;
without changing
return &a;
any function
prototype
}
void main()
{
int *p = GetPtr();
*p = 10;
}

Slid No. 20

ANOTHER VERY COMMON BUG


void func(int *p)
{
p = new int;
*p = 5;
}
void main()
{
int *p1 = NULL
func(p1);
*p1 = 5
}

A copy of
address of p1
was made into p
p was allocated
new memory

The function exits


and we have a
memory leak

What is wrong
here???
Here we are
accessing a memory
location that no
longer exists

CORRECT VERSION
int func(int **p)
{
*p = new int;
**p = 5;
}
void main()
{
int *p1 = NULL
func(&p1);
*p1 = 5
}
Everyone is happy!!!
Slid No. 21

WHAT IS THE OUTPUT???


void allocPtr(int * p)
{
p = new int;
}

void allocPtr(int* & p)


{
p = new int;
}

int main()
{
int *x=NULL;
allocPtr(x);
if (!x)
cout << memory
leak";
else
cout << "allocated";
return 0;

int main()
{
int *x=NULL;
allocPtr(x);
if (!x)
cout << "memory
leak\n";
else
cout << "allocated";

return 0;
}
Slid No. 22

Arrays and Pointers


Name of the array is also a pointer. It points to the first
item of the array.
char alpha[10];
char *alphaptr;
char *letterptr;
alphaptr = alpha;
letterptr = &alpha[0];
0

alpha

alphaptr

letterptr
Slid No. 23

Dynamically Allocated Arrays

//ALLOCATIONS
int *IntArr;
IntArr = new int[10];
char *CharArr;
CharArr = new char[15];
float *FloatArr;
FloatArr = new float[5];

//allocates space for array of 10 integers


//allocates space for array of 15 characters
//allocates space for array of 5 floats

//DELETION FROM MEMORY


delete [] IntArr;
delete [] CharArr;
delete [] FloatArr;

Slid No. 24

More About Arrays and Pointers

char alpha[5] = {a,b,c,d,e};


char *alphaptr;
alphaptr = &alpha[2];

cout <<alphaptr[0]; //will output c


cout <<alphaptr[-1]; //will output b
0
a

alpha

1
b

2
c

3
d

4
e

cout <<alphaptr[2] ; //will output e

alphaptr
Slid No. 25

ARRAYS
void ChangeArray(int *a,int Size)
AllocateArray
arr
{
for (int i=0;i<Size;++i)
a[i] = i;
CallChangeArray
myArrr
}
void AllocateArray(int **arr,int Size)
{
0 1 2 3 4 5 6 7 8 9
*arr = new int[Size];
}
void CallChangeArray()
ChangeArray
a
{
int *myArr = NULL;
AllocateArray(&myArr,10);
CallChangeArray
myArrr
ChangeArray(myArr,10);
}

Note: to change the value inside myArr we have to pass the


address of myArr and to change the elements of the array we can
simply pass myArr

Slid No. 26

2D arrays

if we want to change the


value of my2D we have
to pass the address of
my2D

Allocate2D

arr

CallAllocate2D

my2D

Type of each element is int

void Allocate2D(int ***arr,int row,int


col)
{
*arr = new int*[row]
for (int i=0;i<row;++i)
(*arr)[i]=new
int[col];
}
void CallAllocate2D()
{
int **my2D;
Allocate2D(&my2D,3,4);
}

type of
each
element is
int*

Slid No. 27

POINTERS TO OBJECTS
class Student
{
public:
Student();
~Student();
void Enroll();
float GetGPA();
void ComputeGPA();
private:
float GPA;
char *Name;
};

void functionA()
{
Student S;
S.Enroll();
cout << S.GetGPA();
}

Whats missing???

void functionA()
{
Student *Sptr = new Student;
Sptr->Enroll();
cout << S->GetGPA();
}

Make a note of where we use dot notation and where we use


Slidarrow
No. 28

DEEP Vs. SHALLOW COPY

int *p, *q;


p = new int;
*p = 5;
q = p;

Vs.

int *p, *q;


p = new int;
q = new int;
*p = 5
*q = *p;

DRAW THE PICTURES TO UNDERSTAND

Slid No. 29

MORE ON.DEEP Vs. SHALLOW COPY


class Student
{
public:
Student() {GPA = 4; Name = NULL;};
~Student();
void CopyStudent (Student & S);
void SetName(char *N);
private:
float GPA;
char *Name;
};

void Student::CopyStudent(Student
&S1)
{
S1.GPA = GPA;
S1.Name = Name;
}

void UserOfStudentObjects()
{
Student A,S;
A.SetName(Amna);
A.CopyStudent(S);
}
implement SetName

void Student::CopyStudent(Student &S1)


{
S1.GPA = GPA;
Vs.
S1.Name = new char(strlen(Name)
+1);
strcpy(S1.Name,Name);
}

What is the difference between the two???DRAW THE PICTURES TO UNDERSTA


Slid No. 30

Slid No. 31

Potrebbero piacerti anche