Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

G6DICP

Memory
! Physical ! Each

Lecture 14 Pointers and Dynamic Memory Allocation

memory (RAM) is arranged in bytes.

byte has a physical address (number).

! Data

is stored in a physical byte (or series of bytes). can be accessed by using its physical address.

! Data

Pointers
! Pointers

Pointer Syntax
! The

are a data type that contain memory addresses. pointer can point to a variable of any type (eg a single byte, a string or an entire record). a pointer contains the address of the start of a data construct - pointers are the same size regardless of what they are pointing to. can be untyped or typed (ie what data type they are pointing to may be specified).

^ character
eg var pt1 : ^byte; writeln(pt1^);

^byte - a pointer that is pointing to a byte pt1^ - the data pointed to by pt1
eg

!A

! The

@ character
eg var myVar : byte; pt1 : ^byte; ...

! Because

@myVar - the address of myVar

! Pointers

pt1:=@myVar; writeln(pt1^);

Pointer Behaviour
! Remember! ! Pointers

Dynamic Memory Allocation


! Allocation ! The

of memory is usually automatic.

do not contain data - they contain a reference to data. pointers can point at one data object thus changing the content of one will seemingly change the content of them all. Really only one copy of the data exists.

Heap is an area of memory that can be allocated (and deallocated) while a program is running (ie dynamically). allows programs to re-use memory (eg for arrays of indeterminate size).

! Several

! This

new and dispose


! new

Advantages of Pointers
! Data

allocates memory on the heap deallocates memory ! For example:


! dispose
var myString : ^string; begin new(myString); myString^:=This is a String'; writeln(name^); dispose(myString); end.

can be accessed without physically moving it in memory. ! Dynamic allocation makes much more efficient use of memory - allowing very large data constructs. ! Because pointers point to physical memory they can allow access to data anywhere. ! Some languages make much more extensive use of pointers than does Pascal - eg C and C++.

Problems with pointers


! Be

careful - bug prone.

! It

is easy to accidentally modify data - especially if more than one pointer is pointing at the same data.

! Memory
! If

leaks

memory on the heap is not deallocated correctly, it may retain data even when the program terminates making this memory unavailable to other programs.

You might also like