Anda di halaman 1dari 9

2

Types of Program Data


TypesofProgramData
StaticData:Memoryallocationexiststhroughout
execution of program
executionofprogram
AutomaticData:Automaticallycreatedatfunction
entry,residesinactivationframeofthefunction,
y
g
andisdestroyedwhenreturningfromfunction
DynamicData:Explicitlyallocatedanddeallocated
during program execution by
duringprogramexecution
by
C++instructionswrittenbyprogrammer

261102
Computer Programming
Lecture12:DynamicMemoryAllocation

Allocation of Memory
AllocationofMemory

Dynamic MemoryAllocation
Dynamic
Memory Allocation

StaticAllocation:Allocationofmemoryspace
atcompiletime.
t
il ti

Dynamicallocation isusefulwhen

DynamicAllocation:Allocationofmemory
space at run time
spaceatruntime.

arraysneedtobecreatedwhoseextentisnot
knownuntilruntime
complexstructuresofunknownsize and/orshape
need to be constructed as the program runs
needtobeconstructedastheprogramruns
objectsneedtobecreatedandtheconstructor
argumentsarenotknownuntilruntime

Dynamic MemoryAllocation
Dynamic
Memory Allocation

The new operator

Pointers needtobeusedfordynamicallocation
ofmemory
Usetheoperatornew
Use the operator new todynamicallyallocate
to dynamically allocate
space
Usetheoperatordelete tolaterfreethis
space

Ifmemoryisavailable,thenew operatorallocates
memoryspacefortherequestedobject/array,and
f th
t d bj t/
d
returnsapointerto(addressof)thememory
allocated.
IfsufficientmemoryisNOT
If sufficient memory is NOT available,thenew
available the new
operatorreturnsNULL.
Thedynamicallyallocatedobject/arrayexistsuntil
the delete operatordestroysit.
thedelete
operator destroys it

The delete operator

Dynamic MemoryAllocation
Dynamic
Memory Allocation
&p fe38 p

Thedelete operatordeallocates theobject


orarraycurrentlypointedtobythepointer
which was previously allocated at runtime by
whichwaspreviouslyallocatedatruntimeby
thenew operator.
IfthevalueofthepointerisNULL thereisno
effect.
p
p
p
p
p

=
=
=
=
=

0
0x2f7620
0x2f7620
0x2f7620
0

&p
&p
&p
p
&p
&p

=
=
=
=
=

0x22fe38
0x22fe38
0x22fe38
0x22fe38
0x22fe38

*p = 3111712
*p
p = 69
*p = 3111712

Dynamic MemoryAllocation
Dynamic
Memory Allocation
&p 22fe38 p

10

Dynamic MemoryAllocation
Dynamic
Memory Allocation
&p 22fe38 p

2f7620

newint int
????
2f7620

p
p
p
p
p

=
=
=
=
=

0
0x2f7620
0x2f7620
0x2f7620
0

&p
&p
&p
p
&p
&p

=
=
=
=
=

0x22fe38
0x22fe38
0x22fe38
0x22fe38
0x22fe38

2f7620

newint int
69
2f7620

p
p
p
p
p

*p = 3111712
*p
p = 69
*p = 3111712

=
=
=
=
=

0
0x2f7620
0x2f7620
0x2f7620
0

&p
&p
&p
p
&p
&p

=
=
=
=
=

0x22fe38
0x22fe38
0x22fe38
0x22fe38
0x22fe38

*p = 3111712
*p
p = 69
*p = 3111712

11

Dynamic MemoryAllocation
Dynamic
Memory Allocation
&p 22fe38 p

12

Dynamic MemoryAllocation
Dynamic
Memory Allocation
&p 22fe38 p

2f7620

Dangling
Dangling
Pointer

2f7620

2f7620

????
Freememory
space here
spacehere

p
p
p
p
p

=
=
=
=
=

0
0x2f7620
0x2f7620
0x2f7620
0

&p
&p
&p
p
&p
&p

=
=
=
=
=

0x22fe38
0x22fe38
0x22fe38
0x22fe38
0x22fe38

*p = 3111712
*p
p = 69
*p = 3111712

p
p
p
p
p

=
=
=
=
=

0
0x2f7620
0x2f7620
0x2f7620
0

&p
&p
&p
p
&p
&p

=
=
=
=
=

0x22fe38
0x22fe38
0x22fe38
0x22fe38
0x22fe38

*p = 3111712
*p
p = 69
*p = 3111712

????

13

Dynamic MemoryAllocation
Dynamic
Memory Allocation

14

Dynamic MemoryAllocation
Dynamic
Memory Allocation

Output
p = 0x577620
q = 0x577640

&p = 0x22fe38
&q = 0x22fe30

Output

*p = 69
*q = 55

p = 0x2f7620
q = 0x2f7620
*p = 55

&p = 0x22fe38
&q = 0x22fe30

*p = 69
*q = 55

15

Dynamic allocation of Arrays


Dynamicallocationof
Usethe[array_size] onthenew
statementtocreateanarrayofobjects
instead of a single instance.
insteadofasingleinstance.
Onthedelete statementuse[] to
indicatethatanarrayofobjects istobe
deallocated.
std::vector isthedynamicarraysin
C++.

16

Array of Runtime Bound


ArrayofRuntime
Maybeillegalinsome
complier here arra si e
complierwherearraysize
mustbespecifiedwith
constantvariable(const)

(automaticstorage)

Arrays of Runtime Bound =ArraysofVariableLength


ArraysofRuntimeBound
= Arrays of Variable Length
http://www.openstd.org/jtc1/sc22/wg21/docs/papers/2014/n3875.pdf

17

Dynamic allocation of Arrays


Dynamicallocationof

18

Dynamic allocation of 2DArrays


Dynamicallocationof
Atwodimensionalarrayisreallyanarrayof
arrays(rows).
(
)
To
Todynamicallydeclareatwodimensional
dynamically declare a two dimensional
arrayofint type,youneedtodeclarea
pointertoapointer as:
int **matrix;

Pointer name can used as array name


Pointernamecanusedasarrayname
19

Dynamic allocation of 2DArrays


Dynamicallocationof
Toallocatespaceforthe2Darraywith
T ll
f h 2D
ih
r rowsandc columns:
Youfirstallocatethearrayofpointers
f
ll
h
f
whichwill
h h ll
pointtothearrays(rows)
matrix = new int*[r];

Thiscreatesspaceforr
This creates space for r addresses;eachbeinga
addresses; each being a
pointertoan int.
Thenyouneedtoallocatethespaceforthe1D
Then you need to allocate the space for the 1D
arraysthemselves,eachwithasizeofc
for(i=0;
f
(i 0 i<r;
i
i )
i++)
matrix[i] = new int[c];

20

Dynamic allocation of 2DArrays


Dynamicallocationof
Theelementsofthearray matrix nowcanbe
accessed by the matrix[i][j] notation
accessedbythe
Keepinmind,theentirearrayisnotincontiguous
space (unlikeastatic2Darray)
Theelementsofeachrowareincontiguousspace,but
The elements of each row are in contiguous space but
therowsthemselvesarenot.
matrix[i][j+1] isafter matrix[i][j] in
memory,butmatrix[i][0] maybebeforeor
aftermatrix[i+1][0] inmemory

21

22

Dynamic allocation of 2DArrays


Dynamicallocationof

Array of Runtime Bound


ArrayofRuntime

Input size of your matrix: 2 4


Input row [1]: 1 2 5 8
p
row [
[2]:
] 4 9 9 8
Input
Arrayofarraysofruntimebound
Maybeillegalinsome
complier here arra si e
complierwherearraysize
mustbespecifiedwith
constantvariable(const)

DynamicAllocation
Equivalent to float c[N][M]
Equivalenttofloatc[N][M]

Input size of your matrix: 2 4


p
row [
[1]:
] 1 2 5 8
Input
Input row [2]: 4 9 9 8

Deallocation of2DArray

23

Dynamic allocation of 2DArrays


Dynamicallocationof

24

Dynamic allocation of 2DArrays


Dynamicallocationof

new
new

float**

float*
c[0]
float*
c[1]
float*
c[2]

floatc[0][0]
floatc[0][1]

floatc[0][M]
Notcontiguous
N
t
ti
between2rows

new
float*
c[N]

floatc[1][0]
floatc[1][1]

new
floatc[N][0]
floatc[N][1]

floatc[N][M]

floatc[1][M]

Input size of your matrix:


Input row [1]: 1 2 3 4 5
Input row [2]: 4 5 5 7 5
Input row [3]: 1 2 3 4 5
Input row [4]: 4 5 6 6 7
Input row [5]: 1 5 7 4 7
0x2f7650 0x2f7654 0x2f7658
0x2f7b20 0x2f7b24 0x2f7b28
0x2f7b40 0x2f7b44 0x2f7b48
0x2f7b60 0x2f7b64 0x2f7b68
0x2f7b80 0x2f7b84 0x2f7b88

5 5

0x2f765c
0x2f7b2c
0x2f7b4c
0x2f7b6c
0x2f7b8c

0x2f7660
0x2f7b30
0x2f7b50
0x2f7b70
0x2f7b90

25

Array of Runtime Bound


ArrayofRuntime

26

Memory Leaks
MemoryLeaks
Whenyoudynamicallycreateobjects,youcanaccess
themthroughthepointerwhichisassignedbythe
new operator
Reassigningapointerwithoutdeletingthememory
Reassigning a pointer without deleting the memory it
it
pointedtopreviouslyiscalledamemoryleak
Itresultsinlossofavailablememoryspace

Input
p
size of y
your matrix:
Input row [1]: 1 2 3 4 5
Input row [2]: 6 7 8 9 10
Input row [3]: 4 5 7 8 3
Input row [4]: 1 1 2 2 2
Input row [5]: 1 4 7 5 5
0x22fd40 0x22fd44 0x22fd48
0x22fd54 0x22fd58 0x22fd5c
0x22fd68 0x22fd6c 0x22fd70
0x22fd7c 0x22fd80 0x22fd84
0x22fd90 0x22fd94 0x22fd98

5 5

0x22fd4c
0x22fd60
0x22fd74
0x22fd88
0x22fd9c

0x22fd50
0x22fd64
0x22fd78
0x22fd8c
0x22fda0

27

Memory Leaks
MemoryLeaks
int *ptr1 = new int;
int *ptr2 = new int;
*ptr1 = 8;
* t 2 = 5;
*ptr2
5
ptr2 = ptr1;

Inaccessible Object
ptr1
8

ptr2
5

ptr1
8

How to avoid?

28

ptr2
5

Aninaccessibleobjectisanunnamedobject
that was created by operator new andwhicha
thatwascreatedbyoperatornew
and which a
programmerhasleftwithoutapointertoit.
Itisalogicalerrorandcausesmemoryleaks.

29

Dangling Pointer
DanglingPointer

30

Dangling Pointer
DanglingPointer

Itisapointerthatpointstodynamicmemory
that has been deallocated
thathasbeendeallocated.
g
g gp
Theresultofdereferencingadanglingpointer
isunpredictable.

int *ptr1
ptr1 = new int;
int *ptr2;
p
= 8;
;
*ptr1
ptr2 = ptr1;
delete ptr1;
p

ptr1
8

ptr2

ptr1

How to avoid?

ptr2

31

Dangling Pointer
DanglingPointer

32

Dangling Pointer
DanglingPointer

AutomaticAllocation

AutomaticAllocation
int *
myPtr

int *
myPtr =22fdf4
Dangling
Pointer
&temp=22fdf4

int *
p=22fdf4

int
temp=69

int *
p=22fdf4

int
temp=69
address22fdf4

p = 0x22fdf4
myPtr = 0x22fdf4
*
*myPtr
= 0

p = 0x22fdf4
myPtr = 0x22fdf4
*
*myPtr
= 0

p andtemp aredestroyed
afterleavingfunction

33

Dangling Pointer
DanglingPointer

34

Dangling Pointer
DanglingPointer

DynamicAllocation

StaticAllocation
int *
myPtr =537620

int *
myPtr =4a7034
Dangling
Pointer

int *
p=537620

newint
69

int *
p=4a7034

address=537620

p = 0x537620
myPtr = 0x537620
*myPtr = 69

Beforedelete operator

int
temp=69
&temp=4a7034

p = 0x4a7034
myPtr = 0x4a7034
*myPtr = 69

p isdestroyedafterleaving
is destroyed after leaving
function
temp isnotdestroyed
is not destroyed
afterleavingfunction

Anda mungkin juga menyukai