Transcript Chapter 1

Chapter 6
Data Types
ISBN 0-321—49362-1
Chapter 6 Topics
•
•
•
•
•
•
•
•
•
Introduction
Primitive Data Types
Character String Types
User-Defined Ordinal Types
Array Types
Associative Arrays
Record Types
Union Types
Pointer and Reference Types
Copyright © 2007 Addison-Wesley. All rights reserved.
1-2
Introduction
•
•
•
•
A data type defines a collection of data objects
and a set of predefined operations on those
objects
A descriptor is the collection of the attributes of a
variable used for type checking and to build the
code for the allocation and deallocation
operations.
An object represents an instance of a userdefined (abstract data) type
One design issue for all data types: What
operations are defined and how are they
specified?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-3
Primitive Data Types
• Almost all programming languages provide
a set of primitive data types
• Primitive data types: Those not defined in
terms of other data types
• Some primitive data types are merely
reflections of the hardware
• Others require only a little non-hardware
support for their implementation
Copyright © 2007 Addison-Wesley. All rights reserved.
1-4
Primitive Data Types: Integer
• Almost always an exact reflection of the hardware
so the mapping is trivial
• There may be as many as eight different integer
types in a language
• Java’s signed integer sizes: byte, short, int,
long
• C++, C# include unsigned integer types
• Negative integers
– Sign-magnitude notation where the sign bit is set to
indicate negative and the remainder of the bit string
represents the absolute value of the number.
– Two’s complement
– One’s complement
Copyright © 2007 Addison-Wesley. All rights reserved.
1-5
Primitive Data Types: Floating Point
• Model real numbers, but only as approximations for most real
values
– Representation - 0.1 is 0.0001100110011… in binary
– Calculations may also result in loss of accuracy
• Languages for scientific use support at least two floatingpoint types (e.g., float and double; sometimes more
• Usually exactly like the hardware, but not always
• IEEE Floating-Point
Standard 754
Precision – accuracy of the
fractional part in bits.
Range – combination of the
range of fractions and
exponents.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-6
Primitive Data Types: Complex
• Some languages support a complex type,
e.g., Fortran and Python
• Each value consists of two floats, the real
part and the imaginary part
• Literal form (in Python):
(7 + 3j), where 7 is the real part and 3 is
the imaginary part
Copyright © 2007 Addison-Wesley. All rights reserved.
1-7
Primitive Data Types: Decimal
• For business applications (money)
– Essential to COBOL – PIC S999V99
– C# offers a decimal data type
• Store a fixed number of decimal digits, in
coded form (BCD)
• Advantage: accuracy
• Disadvantages: limited range, wastes
memory
Copyright © 2007 Addison-Wesley. All rights reserved.
1-8
Primitive Data Types: Boolean
• Introduced in Algol 60
• C89 exception –
– C99 and C++ have boolean but also allow
numeric expressions.
• Simplest of all
• Range of values: two elements, one for
“true” and one for “false”
• Could be implemented as bits, but often as
bytes
– Advantage: readability
Copyright © 2007 Addison-Wesley. All rights reserved.
1-9
Primitive Data Types: Character
•
•
•
•
Stored as numeric codings
Most commonly used coding: ASCII
ADA95 uses ISO 8859-1
An alternative, 16-bit coding: Unicode
– First 128 are identical to the ASCII code
– Includes characters from most natural
languages
– Originally used in Java
– Python, Perl, C# and JavaScript also support
Unicode
Copyright © 2007 Addison-Wesley. All rights reserved.
1-10
Character String Types
• Values are sequences of characters
• Design issues:
– Is it a primitive type or just a special kind of array?
– Should the length of strings be static or dynamic?
• Typical operations:
–
–
–
–
–
Assignment and copying
Comparison (=, >, etc.)
Catenation
Substring reference (slices)
Pattern matching
Copyright © 2007 Addison-Wesley. All rights reserved.
1-11
Character String Type in Certain
Languages
•
C and C++
–
–
Not primitive
Use char arrays for implementation
–
Provides a library of functions that provide string operations such as strcpy,
strcmp, strlen and strcat…
• char str [ ] = “apples”;
• C Standard Library problems – Example of strcpy(src, dest) where dest is 20 chars
and src is 50 chars
• C++ programmers should use the string class from its standard library vs. the char
arrays and C string lib
•
SNOBOL4 (a string manipulation language)
•
Fortran –
•
Python –
•
Java
•
Perl, JavaScript, Ruby, and PHP
- Provide built-in pattern matching, using regular
–
–
Primitive
Many operations, including elaborate pattern matching
–
Primitive type with assignment, relational operators, catenation and substring references
–
Primitive type; Immutable; operations for substring reference, catenation, indexing, searching
and replacting.
–
Primitive; Immutatable; operations via the String class
expressions
Copyright © 2007 Addison-Wesley. All rights reserved.
1-12
Pattern matching examples
• /[A-Za-z][A-Za-z\d]+/
– Describes the typical name form in PLs
– Matches strings that begin with a letter, followed by one or more letters
or digits
• /\d+\.?\d*|\.\d+/
– Matches numeric literals
• Strings of one or more digits, possibly follwed by a decimal point,
folllowed by 0 or more digits.
• Strings that begin with a decimal point, followed by one or more digits
[] enclose character classes
\d specifies a digit
+ specifices one or more
\ specifies
\. Specifies a literal decimal point
? Specifies 0 or one occurrences
| separates two alternatives
Copyright © 2007 Addison-Wesley. All rights reserved.
1-13
Character String Length Options
•
Design choices
1. Static Length Strings: COBOL, Python, Ruby and Java’s
respective String classes
2. Limited Dynamic Length Strings: C and C++ (In these
languages, a special character is used to indicate the
end of a string’s characters, rather than maintaining the
length.)
3. Dynamic Length Strings (no maximum): SNOBOL4, Perl,
JavaScript
•
Ada 95 supports all three string length options
–
String, Bounded_String, Unbounded_String
Copyright © 2007 Addison-Wesley. All rights reserved.
1-14
Character String Implementation
•
Static length: compile-time descriptor
•
Limited dynamic length: may need a run-time descriptor for
length (but not in C and C++)
–
–
–
–
•
(StaticString, Length, Address)
Single allocation when string variable is bound to storage
(LimitedDynamicString, MaxLen, CurrentLength, Address)
Single allocation when string variable is bound to storage
Dynamic length: need run-time descriptor; allocation/deallocation is the biggest implementation problem
–
–
(DynamicString, Current Length, Address)
More costly storage management
1. Stored in linked lists
2. Store as arrays of pointers to individual chars
3. Store compleete strings in adjacent storage cells
Copyright © 2007 Addison-Wesley. All rights reserved.
1-15
Compile- and Run-Time Descriptors
Compile-time
descriptor for
static strings
Copyright © 2007 Addison-Wesley. All rights reserved.
Run-time
descriptor for
limited dynamic
strings
1-16
Character String Type Evaluation
• Aid to writability
• As a primitive type with static length, they
are inexpensive to provide--why not have
them?
• Dynamic length is nice, but is it worth the
expense?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-17
Ordinal Types
• An ordinal type is one in which the range of
possible values can be easily associated with the
set of positive integers
• Examples of primitive ordinal types in Java
– integer
– char
– Boolean
• A User-Defined Ordinal Type supported by PLs
– Enumeration
– Subrange
Copyright © 2007 Addison-Wesley. All rights reserved.
1-18
Enumeration Types
•
•
•
•
C and Pascal were the first widely used languages to include
C#, C++, Java 5.0 and later, Ada include this type.
Perl, JavaScript, PHP, Python and Ruby do not.
All possible values, which are named constants, are
enumerated in the definition
• C# example:
enum days {mon, tue, wed, thu, fri, sat, sun};
• Design issues are related to type checking
– Is an enumeration constant allowed to appear in more than one
type definition, and if so, how is the type of an occurrence of
that constant checked?
– Are enumeration values coerced to integer?
– Can any other type coerced to an enumeration type?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-19
Evaluation of Enumerated Type
• Aid to readability
enum colors {RED, BLUE, GREEN};
colors myColor = blue, yourColor=red;
vs.
int RED = 0, BLUE = 1;
• Aid to reliability
– compiler can perform type checking for:
• operations (don’t allow colors to be added)
• No enumeration variable can be assigned a value outside its
defined range as in myColor = 4;
• Ada, C#, and Java 5.0
– enumeration type variables in these languages are not coerced into
integer types
• Exception - C++
– enumeration type variables in these languages are coerced into integer
types so it is possible to have myColor++;
– Also, enum colors {red= 1, blue = 100, green 10000} problems.
• Implementation - implemented as integers
Copyright © 2007 Addison-Wesley. All rights reserved.
1-20
Subrange Types
•
Introduced by Pascal and included in ADA
•
An ordered contiguous subsequence of an ordinal type
•
Ada’s design uses subtypes which are new names for possibly restricted versions of
existing types.
•
–
–
Example: 12..18 is a subrange of integer type
They are type compatible with the parent type.
Example:
type Days is (mon, tue, wed, thu, fri, sat, sun);
subtype Weekdays is Days range mon..fri;
subtype Index is Integer range 1..100;
Day1: Days;
Day2: Weekday;
….
Day2 := Day1;
•
Evaluation
–
–
•
Aid to readability - Makes it clear to the readers that variables of the subrange type can only
store a certain range of values
Reliability - Assigning a value to a subrange variable that is outside the specified range is
detected as an error
Implementation - implemented like the parent types but with additional code inserted
(by the compiler) to restrict assignments to subrange variables
Copyright © 2007 Addison-Wesley. All rights reserved.
1-21
Array Types
• Definition used for discussion
– An array is an aggregate of homogeneous data
elements in which an individual element is
identified by its position in the aggregate,
relative to the first element.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-22
Array Design Issues
•
•
•
•
•
•
•
•
•
What syntax is used for subscripting?
What data types are legal for subscripts?
Are subscripting expressions in element
references range checked?
When are subscript ranges bound?
When does allocation take place?
What is the maximum number of subscripts?
Is there an implicit lower bound?
Can array objects be initialized?
Are any kind of slices supported?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-23
Array Indexing
• Indexing (subscripting) is a mapping from
indices to elements
array_name (index_value_list) 
• Index Syntax
an element
– FORTRAN, PL/I, Ada use parentheses
• Ada explicitly uses parentheses to show uniformity
between array references and function calls because
both are mappings
– Sum := Sum + B(I);
– Most other languages use brackets
• Java – myArray[i] = myArray[i+1];
Copyright © 2007 Addison-Wesley. All rights reserved.
1-24
Arrays Index (Subscript) Types
• Index(Subscript) Types
– FORTRAN, C: integer only
– Ada: integer or enumeration (includes Boolean and char)
•
•
•
•
•
Example:
type Week_Day_Type is (Mon, Tue, Wed, Thu, Fri0;
type Sales is array(Week_Day_Type) of Float;
Sales team1, team2;
team1(Mon) := 500000;
– Perl syntax for access to an element of an array
• @list is $list[1]
• $list[-2] would reference the element second from the end of the array
• Index range checking
- C, C++, Perl, and Fortran do not specify range checking
- Java, ML, C# specify range checking
- In Ada, the default is to require range checking, but it can be
turned off
- Perl, yields undef but no error
Copyright © 2007 Addison-Wesley. All rights reserved.
1-25
Array Categories
Categories are based on the binding to
subscript ranges, bindings to storage and
from where the storage is allocated.
1. Static:
– Subscript Ranges are statically bound.
– Storage Allocation is static (before run-time).
–
Advantage: processing efficiency (no dynamic allocation)
–
Example: C and C++ arrays that include the
static modifier are static.
– static int [5];
Copyright © 2007 Addison-Wesley. All rights reserved.
1-26
Array Categories
2. Fixed stack-dynamic:
–
–
Subscript Ranges are statically bound.
Storage Allocation is done when execution reaches the
code to which the declaration is attached at run time.
(i.e. at declaration elaboration time)
–
Both ranges and storage binding remain fixed thereafter.
–
Advantage: space efficiency.
–
Example: Arrays that are declared in C and C++
functions without the static modifier. int [5];
Copyright © 2007 Addison-Wesley. All rights reserved.
1-27
Array Categories (continued)
3. Stack-dynamic:
– Subscript Ranges are dynamically bound at declaration
elaboration time.
– Storage Allocation is dynamically performed at declaration
elaboration time.
– Remain fixed for the lifetime of the variable.
– Advantage: flexibility (the size of an array can be
determined at run time.)
– Example: ADA
Get (List_Len)
Declare
List : array (1 ..List_Len) of Integer;
begin
…
end;
Copyright © 2007 Addison-Wesley. All rights reserved.
1-28
Array Categories (continued)
4. Fixed heap-dynamic:
– Subscript Ranges are dynamically bound at run time upon
request by the user.
– Storage Binding is dynamically performed upon request as
well.
– Both ranges and storage binding remain fixed thereafter.
– Storage is allocated from the heap.
– Example: Fortran 95, C (malloc and free) and C++ (new
and delete) ; Java – int [] myArray = new int[num_items];
Copyright © 2007 Addison-Wesley. All rights reserved.
1-29
Array Categories (continued)
5. Heap-dynamic:
–
–
–
–
Subscript Ranges are dynamically bound.
Storage Allocation is also dynamic.
Can change any number of times
Advantage: flexibility (arrays can grow or shrink during program
execution)
– Examples:
• Perl –
– push adds one or more new elements on the end of the array
– unshift – puts one or more new elements on the beginning of the array
– Shrinks the array by assigning it to the empty list ().
• Javascript supports sparse arrays meaning that subscripts do not have to
be contiguous.
–
–
Assume that array list has 10 elements with subscripts 0..9
list[50] = 42; would add an 11th element. Now the array will have a length of 51,
where the elements at subscripts 11..40 undefined.
• Ruby – made to grow via methods; supports negative subscripts;
references to non existent items yields nil but no error.
• Python – made to grow via methods; does not supports negative
subscripts ; references to non existent items yields a run-time error.
• C# includes a second array class ArrayList that provides fixed heapdynamic
Copyright © 2007 Addison-Wesley. All rights reserved.
1-30
Heterogeneous Arrays
• A heterogeneous array is one in which the
elements need not be of the same type
• Supported by
– Perl
• Elements can be any mixture of scalar types, which
includes numbers, strings, and references.
– Javacript
• Elements can be any type.
– Python and Ruby
• Elements can be references to objects of any type
Copyright © 2007 Addison-Wesley. All rights reserved.
1-31
Array Initialization
• Some language allow initialization at the time of storage
allocation
– Fortran95
• Example: Integer, Dimension (3) :: List = (/0,5,5/)
– C, C++, Java, C#
• Example:
int list [] = {4, 5, 7, 83}
• Example:
char name [] = “freddie”;
– Character strings in C and C++
– Arrays of strings in C and C++
• Example: char *names [] = {“Bob”,“Jake”,“Joe”];
– Java initialization of String objects
• Example: String[] names = {“Bob”,“Jake”,“Joe”};
– Ada
• Example:
• List: array (1..5) of Integer := (1,3,5, 7,9);
• Bunch: array(1..5) of Integer := (1 => 17, 3=>34,
others =>0);
Copyright © 2007 Addison-Wesley. All rights reserved.
1-32
Arrays Operations
• An array operation is one that operates on the array as a unit, such
as assignment, catenation, comparison for equality/inequality and
slices.
• APL provides the most powerful array processing operations for
vectors and matrixes as well as unary operators (for example, to
reverse column elements)
• Fortran provides elemental operations because they are between
pairs of array elements
– For example, + operator between two arrays results in an array of the
sums of the element pairs of the two arrays; Also overloads assignment,
arithmetic, relational and logical operators
– Includes functions for matrix multiplication, transposition and vector dot
products.
• Array catenation
– Ada, Python, Ruby
• Array assignment
– Ada, Perl, Python but they are only reference changes.
• Element membership operations
– Python (in)
• Comparison for equality/inequality
– Python (is) and (==)
Copyright © 2007 Addison-Wesley. All rights reserved.
1-33
Rectangular and Jagged Arrays
• A rectangular array
– A multi-dimensioned array in which all of the rows have the
same number of elements and all columns have the same
number of elements
• Syntax: myArray[3, 7]
• Supported by:
– Fortran, Ada
– C#
• A jagged matrix
– Has rows with varying number of elements
– Possible when multi-dimensioned arrays actually appear as
arrays of arrays
• Syntax: myArray[3][7]
• Supported by:
– C, C++, and Java support jagged arrays
– C#
Copyright © 2007 Addison-Wesley. All rights reserved.
1-34
Slices
• A slice is some substructure of an array;
– a referencing mechanism
• Slices are only useful in languages that
have array operations
• Supported by:
– Fortran 95
– Perl, Python, Ruby,
– Ada (highly restricted version)
Copyright © 2007 Addison-Wesley. All rights reserved.
1-35
Slices Examples in Fortran 95
Copyright © 2007 Addison-Wesley. All rights reserved.
1-36
Slice Examples
• Fortran 95
Integer, Dimension (10) :: Vector
Integer, Dimension (3, 3) :: Mat
Integer, Dimension (3, 3) :: Cube
• Slice Examples:
Vector (3:6) is a four element array
Mat (:, 2) refers to the 2nd column of Mat
Mat(3,: ) refers to the 3rd row of Mat
• Each one can be used as a singly dimensioned
array.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-37
Copyright © 2007 Addison-Wesley. All rights reserved.
1-38
Implementation of Arrays
• Access function maps subscript expressions to an
address in the array
• Access function for single-dimensioned arrays:
– If the lower bound is a fixed number, say 1, then:
• address(list[k]) =
address (list[1]) + ( ( k-1 ) * element_size)
Which simplifies to:
(address (list[1]) – element_size) + (k * element_size)
Note that if statically bound, then the value of the constant
part can be computed before run time.
– If lower bound is not fixed then,
• address(list[k]) =
address (list[lower_bound]) + ((k-lower_bound) * element_size)
Copyright © 2007 Addison-Wesley. All rights reserved.
1-39
Copyright © 2007 Addison-Wesley. All rights reserved.
1-40
Implementing Multi-dimensioned Arrays
• Multi-dimensioned arrays must be mapped to
linear memory.
• Given this 3 x 3 array:
347
625
138
• There are two common ways:
– Row major order (stored by rows) – used in most
languages
• 3, 4, 7, 6, 2, 5, 1, 3, 8
– Column major order (stored by columns) – used in Fortran
• 3, 6, 1, 4, 2, 3, 7, 5, 8
Copyright © 2007 Addison-Wesley. All rights reserved.
1-41
Accessing an Element in a Multi-dimensioned Array
Location (a[i,j]) = address of a [row_lb,col_lb] +
(((i - row_lb) * n) + (j - col_lb)) * element_size
Copyright © 2007 Addison-Wesley. All rights reserved.
1-42
Compile-Time Descriptors
Single-dimensioned array
Copyright © 2007 Addison-Wesley. All rights reserved.
Multi-dimensional array
1-43
Associative Arrays
•
•
An associative array is an unordered collection of
data elements that are indexed by an equal
number of values called keys
–
User-defined keys must be stored
Supported by Perl, Python (dictionaries), Ruby,
PHP
• Used when paired data is to be stored and
searches are a major operation vs. sequential
processing of all elements.
• Design issues:
- What is the form of references to elements?
- Is the size static or dynamic?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-44
Associative Arrays in Perl
•
•
•
Names begin with %; literals are delimited by parentheses
%salaries = (“Gary” => 75000,
“Perry” => 57000,
“Mary” => 55750,
“Cedric” => 47850);
%hi_temps = ("Mon" => 77, "Tue" => 79, “Wed” => 65, …);
Subscripting is done using braces and keys
$salaries{“Perry”} = 58850;
$hi_temps{"Wed"} = 83;
Elements can be removed with delete
delete $salaries{“Gary”};
delete $hi_temps{"Tue"};
•
Delete the entire hash with
@salaries = ();
•
Determine existence with
•
•
Also, keys, values and each operators
Implementation
If (exists $salaries{“Shelly”}) …
–
Provides fast lookups and relatively fast reorganizations
Copyright © 2007 Addison-Wesley. All rights reserved.
1-45
Record Types
• A record is a possibly heterogeneous
aggregate of data elements in which the
individual elements are identified by names
• Design issues:
– What is the syntactic form of references to the
field?
– Are elliptical references allowed (vs. fully
qualified field references…)
Copyright © 2007 Addison-Wesley. All rights reserved.
1-46
Definition of Records in COBOL
• COBOL uses level numbers to show nested
records; others use recursive definition
01 EMP-REC.
02 EMP-NAME.
05 FIRST PIC X(20).
05 MID
PIC X(10).
05 LAST PIC X(20).
02 HOURLY-RATE PIC 99V99.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-47
Definition of Records in Ada
• Records cannot be anonymous in Ada.
type Emp_Name_Type is record
First: String (1..20);
Mid: String (1..10);
Last: String (1..20);
end record;
type Emp_Rec_Type is record
Emp_Name: Emp_Name_Type;
Hourly_Rate: Float;
end record;
Emp_Rec: Emp_Rec_Type;
Copyright © 2007 Addison-Wesley. All rights reserved.
1-48
References to Records
•
Record field reference Examples:
COBOL
field_name OF record_name_1 OF ... OF record_name_n
MID OF EMP_NAME OF EMP_REC
Ada (dot notation)
record_name_1.record_name_2. ... record_name_n.field_name
Emp_Rec.Emp_Name.Mid
•
Fully qualified references must include all record names
•
Elliptical references allow leaving out record names as long
as the reference is unambiguous
–
COBOL
•
MID, MID OF EMP_NAME, MID OF EMP_REC
Copyright © 2007 Addison-Wesley. All rights reserved.
1-49
Operations on Records
• Assignment is very common if the types are
identical
• Ada allows record comparison
• Ada records can be initialized with
aggregate literals
• COBOL provides MOVE CORRESPONDING
– Copies a field of the source record to the
corresponding field in the target record
– SEE PAGES 285-286
Copyright © 2007 Addison-Wesley. All rights reserved.
1-50
Evaluation and Comparison to Arrays
• Records are used when collection of data
values is heterogeneous
• Access to array elements is much slower
than access to record fields, because
subscripts are dynamic (field names are
static)
• Dynamic subscripts could be used with
record field access, but it would disallow
type checking and it would be much slower
Copyright © 2007 Addison-Wesley. All rights reserved.
1-51
Implementation of Record Type
Offset address relative to
the beginning of the records
is associated with each field
Copyright © 2007 Addison-Wesley. All rights reserved.
1-52
Union Data Type
• A union is a type whose variables are
allowed to store different type values at
different times during execution
• Design issues
– Should type checking be required?
– Should unions be embedded in records?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-53
Discriminated vs. Free Unions
• free union - union construct in which there is no language
support for type checking.
– Fortran, C, and C++
– Example:
union flextype {
int intE1;
float floatE1;
union flextype el1;
float x;
…
e11.intE1 = 27;
x = el1.floatE1;
• discriminanted union – union construct in which there is
language support for type checking.
– The construct requires that each union include a type indicator
called a discriminant
– Ada
– Example: see next slide
Copyright © 2007 Addison-Wesley. All rights reserved.
1-54
Ada Union Types
type Shape is (Circle, Triangle, Rectangle);
type Colors is (Red, Green, Blue);
type Figure (Form: Shape) is record
Filled: Boolean;
Color: Colors;
case Form is
when Circle => Diameter: Float;
when Triangle =>
Leftside, Rightside: Integer;
Angle: Float;
when Rectangle => Side1, Side2: Integer;
end case;
end record;
Copyright © 2007 Addison-Wesley. All rights reserved.
1-55
Ada Union Type Illustrated
A discriminated union of three shape variables
Copyright © 2007 Addison-Wesley. All rights reserved.
1-56
Evaluation of Unions
• Free unions are unsafe since they do not
allow type checking
• Java and C# do not support unions
– Reflective of growing concerns for safety in
programming language.
• Ada’s descriminated unions are safe.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-57
Copyright © 2007 Addison-Wesley. All rights reserved.
1-58
Pointer Types
• A pointer type variable has a range of values that
consists of memory addresses and a special value,
nil
• Pointers can be used for indirect addressing.
• Pointers can be used to manage dynamic memory.
– Used to access a location in the area where storage is
dynamically created (usually called a heap)
– Explicit allocation operation provided for the management
of the heap.
• C – malloc
• Java – new
• Provide writability when implementing dynamic
structures like trees.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-59
Pointer Types
• PL/I was the first HLL to include pointer
variables.
– Pointers in this language could be used to refer
to both heap-dynamic variables and other
program variables.
• Some more recent languages, such as Java,
have replaced pointers of this type with
reference types, which, along with implicit
deallocation, minimize the main problems
with pointers.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-60
Design Issues of Pointers
• What should the scope of and lifetime of a pointer variable
be?
• What should the lifetime of a heap-dynamic variable be?
• Should pointers be restricted as to the type of value to which
they can point?
• Should they be used for dynamic storage management,
indirect addressing, or both?
• Should the language support pointer types, reference types,
or both?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-61
Pointer Operations
• Two fundamental operations:
– Assignment
• Used to set a pointer variable’s value to a useful
address
– Dereferencing
• Yields the value stored at the location represented
by the pointer’s value
• Can be explicit or implicit
– Example: C++ uses an explicit operation via *
Copyright © 2007 Addison-Wesley. All rights reserved.
1-62
Pointer Assignment Illustrated
int * ptr;
*ptr = 206;
int j = *ptr; // j
now contains
206
The assignment operation j = *ptr;
Copyright © 2007 Addison-Wesley. All rights reserved.
1-63
Pointers to Records
• In C and C++ , there are two
syntactical forms.
(*p).age or
p -> age
• In Ada
p.age
Copyright © 2007 Addison-Wesley. All rights reserved.
1-64
Pointers in C and C++
•
Extremely flexible but must be used with care; Pointers can point at any variable
regardless of when or where it was allocated; Used for dynamic storage management and
addressing; Explicit dereferencing (*) and address-of (&) operators
int *ptr;
int count;
int init = 3;
…
ptr = &init;
count = *ptr; // count now contains the value 3.
//Same effect as count = init;
•
Pointer arithmetic is possible: Example: ptr + index is valid;
–
This feature is used in array processing.
int list [10];
//declare an array of 10 ints
int *ptr = list; //declare pointer variable;
//init to address of first array element.
*(ptr + 1] is the same as list[1];
*(ptr + index) is the same as list[index];
Note: ptr[index] is the same as list[index];
•
Generic pointers - (void *) , where void * can point to any type; Type checking not
needed since they cannot be de-referenced; Useful in parameter passing.
Pointer Arithmetic in C and C++
float stuff[100];
float *p;
p = stuff;
*(p+5) is equivalent to stuff[5] and p[5]
*(p+i) is equivalent to stuff[i] and p[i]
Copyright © 2007 Addison-Wesley. All rights reserved.
1-66
Pointers in Ada
• Called access types can only point to the heapdynamic variables.
• Since heap-dynamic variables can be referenced by
only one type, when the scope of that type
declaration is reached, no pointers can be left
pointing to the dynamic variable.
• The lost heap-dynamic variable problem is not
eliminated entirely by Ada due to
UNCHECKED_DEALLOCATION
Copyright © 2007 Addison-Wesley. All rights reserved.
1-67
Representations of Pointers
• Large computers use single values
• Intel microprocessors use two 16-bit
cells, one for the segment address and
the other for the offset.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-68
Evaluation of Pointers
• Pointers or references are necessary for
dynamic data structures--so we can't
design a language without them
• Pointers are like goto's--they widen the
range of cells that can be accessed by a
variable
• Dangling pointers and dangling objects are
problems as is heap management.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-69
Problems with Pointers
•
Dangling pointers (dangerous)
–
–
Occur when a pointer points to a heap-dynamic variable that has been deallocated.
C++ Example:
int * arrayPtr1;
int * arrayPtr2 = new int[100];
arrayPtr1 = arrayPtr2;
delete [] arrayPtr2
arrayPtr2 = 0;
// arrayPtr1 is now dangling
•
Lost heap-dynamic variable
–
–
An allocated heap-dynamic variable becomes inaccessible to the user’s program, but has not been
deallocated. (often called garbage)
C++ Example:
int * p1 = new int[100]; //Pointer p1 points to a newly created heap-dynamic
variable
…
p1 = new int[200];
dynamic variable
//p1 is later set to point to a newly created heap-
• Memory allocated by the first assignment of p1 was not deallocated (via delete) and
therefore is still “in use”.
–
The process of losing heap-dynamic variables is called memory leakage.
Solutions for the Dangling Pointer Problem
1. Tombstone: A special cell in the heap that is itself a pointer to the
heap-dynamic variable.
– The actual pointer variable points only at a tombstone.
– When heap-dynamic variable de-allocated, the tombstone is set to nil,
but remains allocated in memory.
– In the case of an invalid pointer, the error can be detected.
– Disadvantage: Costly in time and space
2. Locks-and-keys:
–
Pointer values - (key, address) pairs.
– Heap-dynamic variables -
• Header cell for an integer lock value.
• storage for the variable
– When heap-dynamic variable allocated, a lock value is created and placed
in the variable’s lock cell and in the key cell of its corresponding pointer.
– When a reference is made to a heap-dynamic variable the key of the
pointer is compared to the lock value of the variable.
• If they match, access granted; otherwise a run-time error occurs.
– When the variable is deallocated, its lock value is cleared to an illegal lock
value.
3. Take the deallocation of heap-dynamic variables out of the hands of
the programmers.
– Let the run-time system implicitly deallocate heap-dynmaic variable
when they are no longer used.
• Used by LISP, Java, C# reference variables.
Reference Types
• C++ includes a special kind of pointer type
called a reference type that is used
primarily for formal parameters.
– Advantages of both pass-by-reference and
pass-by-value.
• Java extends C++’s reference variables and
allows them to replace pointers entirely.
– References are references to objects, rather than
being addresses.
• C# includes both the references of Java and
the pointers of C++.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-72
Heap Management
• A very complex run-time process.
• Single-size cells vs. variable-size cells.
• Two approaches to reclaim garbage
– Reference counters (eager approach):
• Reclamation is incremental, occurring as
inaccesssible cells are created.
– Mark-and-Sweep (lazy approach):
• Reclamation occurs when the list of variable space
becomes empty.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-73
Reference Counter
• Reclamation is incremental, occurring when inaccesssible cells are
created.
– Maintains a counter in every cell which stores the number of pointers
currently pointing at that cell.
– When a pointer is disconnected from a cell, this counter is decremented.
– When the counter goes to zero, i.e. the cell has become garbage, it is
returned to free storage.
– Potential Disadvantages:
• Space required for counters;
• Execution time required for frequent pointer changes;
–
Addressed by deferred reference counting
–
Solution by Friedman and Wise.
• Complications for cells connected circularly.
– Advantage: it is intrinsically incremental, so significant delays in the
application execution are avoided.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-74
Mark-and-Sweep
•
•
•
Reclamation occurs only when the list of available space becomes
empty.
The run-time system allocates storage cells as requested and
disconnects pointers from cells as necessary.
When the free list becomes empty, mark-sweep then begins.
–
Every heap cell has an indicator bit which when set indicates that
the cell is garbage and when not set indicates that the cell is
“reachable”.
–
Phases:
1.
2.
3.
–
Init: All cells in the heap have their indicator set (i.e. marking them as garbage.)
Mark: Every pointer in the program is traced into the heap, and all reachable cells are
marked as not being garbage.
Sweep: All garbage cells are then returned to list of available cells.
Disadvantages:
•
•
•
Original form, it was done too infrequently, so when done, it
caused significant delays in application execution.
Contemporary mark-sweep algorithms avoid this by doing it more
often—called incremental mark-sweep
Other “incremental” type algorithms operate on portions of
memory at at time.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-75
Marking Algorithm
for every pointer r do
mark ( r )
void mark (void * ptr) {
if (ptr != 0)
if (*ptr.marker is not marked) {
set *ptr.marker
mark(8ptr.llink)
mark(*ptr.rlink)
}
}
Copyright © 2007 Addison-Wesley. All rights reserved.
1-76
Revisit Dangling Pointers
• Dangling Pointers may also be called Dangling
References…
– Slightly different C Version of previous example:
int *arrayPtr1;
int *arrayPtr2 = (int *) malloc(sizeof(int));
arrayPtr1 = arrayPtr2;
free(arrayPtr2);
• Identify those variables that are aliases.
• Identify the dangling pointers (i.e. references)
Copyright © 2007 Addison-Wesley. All rights reserved.
1-77
Revisit EBNF
Consider the EBNF grammar for numeric
constants below.
<constant> ::= <unsigned integer> | <decimal number>
| <decimal fraction>
<digit>
::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<decimal number>
::= <unsigned integer> <decimal fraction>
<decimal fraction> ::= .<unsigned integer>
<unsigned integer> ::= <digit> | <unsigned integer> <digit>
Which constants would be accepted by this grammar?
Copyright © 2007 Addison-Wesley. All rights reserved.
1-78
Variable-Size Cells
• All the difficulties of single-size cells plus
more.
• Required by most programming languages.
• If mark-sweep is used, additional problems
occur.
– The initial setting of the indicators of all cells in
the heap is difficult.
• Addressed by including a “size” field for each cell.
– The marking process in nontrivial.
– Maintaining the list of available space is another
source of overhead.
Copyright © 2007 Addison-Wesley. All rights reserved.
1-79
Summary
• The data types of a language are a large part of
what determines that language’s style and
usefulness
• The primitive data types of most imperative
languages include numeric, character, and Boolean
types
• The user-defined enumeration and subrange types
are convenient and add to the readability and
reliability of programs
• Arrays and records are included in most languages
• Pointers are used for addressing flexibility and to
control dynamic storage management
Copyright © 2007 Addison-Wesley. All rights reserved.
1-80