Date post: | 17-Jan-2016 |
Category: |
Documents |
Upload: | lorena-murphy |
View: | 224 times |
Download: | 0 times |
11
COSC3306:COSC3306:Programming ParadigmsProgramming Paradigms
Lecture 3: DesignLecture 3: DesignSpecifications PrinciplesSpecifications Principles
Haibin Zhu, Ph.D.Haibin Zhu, Ph.D.Computer ScienceComputer ScienceNipissing University Nipissing University
(C) 2003(C) 2003
22
ContentsContents
AbstractionAbstraction
Parameters and Parameters TransmissionParameters and Parameters Transmission
Exception and Exception HandlingException and Exception Handling
ExpressionsExpressions
Static and Dynamic EnvironmentStatic and Dynamic Environment
33
AbstractionsAbstractions
An An abstractionabstraction is a representation of an is a representation of an object that ignores what could be object that ignores what could be considered as irrelevant details of that considered as irrelevant details of that object.object.
Programming language abstraction falls Programming language abstraction falls into two general categories:into two general categories:– Data AbstractionData Abstraction– Control AbstractionControl Abstraction
44
Data abstractionData abstraction
Data abstractionData abstraction deals with the program deals with the program components that are subject to components that are subject to computation, such as character strings or computation, such as character strings or numbers.numbers.
In other words, data abstraction is based In other words, data abstraction is based on the properties of the data objects and on the properties of the data objects and operations on those objectsoperations on those objects
55
Basic Data AbstractionBasic Data Abstraction
Refers to the internal representation of common data Refers to the internal representation of common data values in a computer system.values in a computer system.For example, in CFor example, in C
intint x;x;floatfloat y;y;
charchar z;z;x is declared as the name of a variable with the data type x is declared as the name of a variable with the data type intint, y is declared as the name of a variable with the data , y is declared as the name of a variable with the data type type realreal, and z is declared as the name of a variable with , and z is declared as the name of a variable with the data type the data type charchar. Each declaration then can address a . Each declaration then can address a variable and define its type. In general, a data type can variable and define its type. In general, a data type can define a type as a set of values that a variable might take define a type as a set of values that a variable might take on. on.
66
Structured Data AbstractionStructured Data Abstraction
It is the principal method for abstracting It is the principal method for abstracting collections of data values that are related.collections of data values that are related.For example, a person includes a name, For example, a person includes a name, address, phone number, and salary, each of address, phone number, and salary, each of which may be a different data type but together which may be a different data type but together represent the record as a whole. represent the record as a whole. Variables can be given a data structure via a Variables can be given a data structure via a declaration, as in Cdeclaration, as in C
intint list[10];list[10];which establishes the variable list as an array of which establishes the variable list as an array of 10 integer values. 10 integer values.
77
Unit Data AbstractionUnit Data Abstraction
It is the principal method for collecting all the It is the principal method for collecting all the information needed to create and use a particular information needed to create and use a particular data type in one unit location. The typical scope of data type in one unit location. The typical scope of unit data abstraction is a module, which is a set of unit data abstraction is a module, which is a set of statements formed as a block to carry out a statements formed as a block to carry out a specific process. specific process. Advantages of using unit data abstraction include Advantages of using unit data abstraction include the following:the following:– The simplicity of program units makes them easier to The simplicity of program units makes them easier to
read.read.– The reusability of program units allows a block to be The reusability of program units allows a block to be
used in many different programming environments. used in many different programming environments. – The independence of program units ensures that the The independence of program units ensures that the
actions of a block are independent of its use. actions of a block are independent of its use.
88
ADA’s UNITADA’s UNITFor each For each UnitUnit which is a unit type, the following operators which is a unit type, the following operators are defined: are defined: – function "*" (Left : Unit; Right : Float_Type) return Unit; function "*" (Left : Unit; Right : Float_Type) return Unit; – function "*" (Left : Float_Type; Right : Unit) return Unit; function "*" (Left : Float_Type; Right : Unit) return Unit; – function "/" (Left : Unit; Right : Float_Type) return Unit; function "/" (Left : Unit; Right : Float_Type) return Unit; – function "/" (Left : Unit; Right : Unit) return Float_Type; function "/" (Left : Unit; Right : Unit) return Float_Type;
The following operators are declared abstract: The following operators are declared abstract: – function "*" (Left : Unit; Right : Unit) return Unit is abstract; function "*" (Left : Unit; Right : Unit) return Unit is abstract; – function "/" (Left : Unit; Right : Unit) return Unit is abstract; function "/" (Left : Unit; Right : Unit) return Unit is abstract;
The implicit declarations of operators "+" and "-" are used The implicit declarations of operators "+" and "-" are used without alteration. without alteration. Fundamental units (those that are not derived from any Fundamental units (those that are not derived from any other units) have these operations only. other units) have these operations only.
99
Control AbstractionControl Abstraction
It describes the order in which statements It describes the order in which statements or groups of statements (program blocks) or groups of statements (program blocks) are to be executed. It deals with the are to be executed. It deals with the components of the program that transfer components of the program that transfer control (e.g., loops, conditional control (e.g., loops, conditional statements, and procedure calls). statements, and procedure calls). Control abstraction may be classified as Control abstraction may be classified as basic, structured, and unit control basic, structured, and unit control abstractions. abstractions.
1010
Basic Control AbstractionBasic Control Abstraction
A typical basic control abstraction is an A typical basic control abstraction is an assignment statement that abstracts the assignment statement that abstracts the computation and storage of a value to the computation and storage of a value to the location given by a variable, as inlocation given by a variable, as in
x=x+5;x=x+5;
which indicates that the old value of x is which indicates that the old value of x is increased by 5 to obtain the new value of increased by 5 to obtain the new value of the variable.the variable.
1111
Structured Control AbstractionStructured Control Abstraction
Sometimes referred to as a Sometimes referred to as a subprogram, subprogram, function,function, or or subroutinesubroutine..For exampleFor example SubroutineSubroutine Name (Parameters)Name (Parameters)
……{body of the subroutine}{body of the subroutine}……ReturnReturnEndEnd
Name is the identification name of the subroutine.
Parameters is a list of the names of variables that represent different values each time the subroutine is called.
This subroutine can be invoked by a call statement within the program. This method is sometimes referred to as subprogram invocation or activation. The Return statement in the callee passes control back to the caller, which resumes execution at the statement following CALL.
1212
Parameters and Parameter Parameters and Parameter TransmissionTransmission
The terms The terms parameterparameter and and parameter parameter transmissiontransmission apply to data sent to and apply to data sent to and returned from the subprograms through a returned from the subprograms through a variety of language mechanisms.variety of language mechanisms.
In this concept, the terms In this concept, the terms actual parameteractual parameter and and formal parameterformal parameter become central. become central.
A formal parameter is a particular kind of A formal parameter is a particular kind of local data object within a subprogram. local data object within a subprogram.
1313
For exampleFor example
intint Max(int X, int Y)Max(int X, int Y){{ifif (X (X Y) Y)
return X;return X;elseelse
return Y;return Y;}}
defines two formal parameters named X and Y and defines two formal parameters named X and Y and declares the type of each one. declares the type of each one. An actual parameter is a data object that is shared with An actual parameter is a data object that is shared with the caller subprogram. the caller subprogram.
1414
A programA program#include #include stdio.hstdio.hmain ( )main ( )
{{intint A, B, C;A, B, C;int Max(int, int);int Max(int, int);A A 10; 10;B B 20; 20;C C Max(A, B); Max(A, B);printf(“ The Maximum of %d and printf(“ The Maximum of %d and %d is %d ”, A, B, C);%d is %d ”, A, B, C);}}
intintMax(int X, int Y)Max(int X, int Y){{ifif (X (X Y) Y)
return X;return X;elseelse
return Y;return Y;}}
A and B in main program are called actual parameters, while X and Y in subprogram Max are called formal parameters.
1515
Semantics Models of Parameter Semantics Models of Parameter PassingPassing
In general, the relation between formal In general, the relation between formal parameters and actual parameters can be parameters and actual parameters can be characterized by one of the following three characterized by one of the following three distinct semantics models:distinct semantics models:– In ModeIn Mode– Out ModeOut Mode– InOut ModeInOut Mode
1616
In Mode parameterIn Mode parameter
Formal parameters receive data from the Formal parameters receive data from the corresponding actual parameter as corresponding actual parameter as illustrated in the following.illustrated in the following.Calling subprogramCalling subprogram Called subprogramCalled subprogram
Max(A, B)Max(A, B) {Call A {Call A X } X } Max(X, Y)Max(X, Y)
1717
Out parameterOut parameter
Formal parameters transmit data to the Formal parameters transmit data to the actual parameter as depicted illustrated in actual parameter as depicted illustrated in the following.the following.Calling subprogramCalling subprogram Called subprogramCalled subprogram
Max(A, B)Max(A, B) {Call A {Call A X} X} Max(X, Y)Max(X, Y)
{Return B {Return B Y} Y}
1818
InOut ModeInOut Mode parameter parameter
Formal parameters can behave as In Formal parameters can behave as In Mode and Out Mode as illustrated in the Mode and Out Mode as illustrated in the following.following.Calling subprogramCalling subprogram Called subprogramCalled subprogram
Max(A, B)Max(A, B) {Call A {Call A X} X} Max(X, Y)Max(X, Y)
{Return A {Return A X} X}
1919
Implementation of the parameter Implementation of the parameter passingpassing
by Constant-Valueby Constant-Value– In C, Max (25,36)In C, Max (25,36)
by Reference by Reference – change(y);change(y);
In Pascal, procedure change (var x:integer)In Pascal, procedure change (var x:integer)– beginbegin
x := x+1;x := x+1;
– endend
In C, void change(int *x)In C, void change(int *x)
{*x = *x+1;{*x = *x+1;
}}
2020
ImplementationImplementation
by Name: most difficultby Name: most difficult– Void Swap (int A, int B)Void Swap (int A, int B)– Swap (x, y[x])??? Ex. Callbyname.cppSwap (x, y[x])??? Ex. Callbyname.cpp
by Resultby Result– Similar to by referenceSimilar to by reference
by Value-Result (by copy)by Value-Result (by copy)
2121
by Value-Result (by copy)by Value-Result (by copy)
in A = 10;in A = 10; fun (int X)fun (int X) { int A;{ int A; X =5;X =5; A = 2;A = 2;}} main_fun()main_fun() {{ fun(A);fun(A); printf(“%d”, A); //5 by copy, 2 by referenceprintf(“%d”, A); //5 by copy, 2 by reference }}
2222
Exceptions and Exception Exceptions and Exception HandlingHandling
An An exceptionexception is any unexpected or infrequent is any unexpected or infrequent event detectable either by hardware or software event detectable either by hardware or software and that may require special attention.and that may require special attention.
Typical exceptions Typical exceptions – runtime errors, runtime errors, – disk read errors, disk read errors, – out-of-range array subscripts, out-of-range array subscripts, – division by zero, or division by zero, or – arithmetic overflow . arithmetic overflow .
2323
ExceptionException
An exception is An exception is raisedraised or or signaledsignaled when its when its association event occurs.association event occurs.
The occurrence of an exception might The occurrence of an exception might implicitly transfers control to an implicitly transfers control to an appropriate unit, called an appropriate unit, called an exception exception handlerhandler, which deals with that particular , which deals with that particular exception.exception.
2424
ExampleExample
One simple exception handling mechanism is that One simple exception handling mechanism is that provided by the BASIC programming language. For provided by the BASIC programming language. For example, the statementexample, the statement
ON ERROR GOTO 100ON ERROR GOTO 100transfers control to line number 100, if any error occurs. transfers control to line number 100, if any error occurs. At line 100 an error handler is written, which ends with At line 100 an error handler is written, which ends with one of three following statements.one of three following statements.– RESUME: transfers control back to the beginning of the line RESUME: transfers control back to the beginning of the line
where the error occurred.where the error occurred.– RESUME NEXT: transfers control to the line following the line RESUME NEXT: transfers control to the line following the line
where the error occurred.where the error occurred.– RESUME Line-Number: transfers control to the specified line RESUME Line-Number: transfers control to the specified line
number. number.
2525
AdvantagesAdvantages
The code required to detect unexpected events can The code required to detect unexpected events can complicate a program.complicate a program.A single exception handler to be used for a large number A single exception handler to be used for a large number of different program units.of different program units.A language encourages its users to consider all of the A language encourages its users to consider all of the events that could occur during program execution and events that could occur during program execution and how they can be handled.how they can be handled.Exception handling separates error-handling code from Exception handling separates error-handling code from normal programming tasks, thus making programs normal programming tasks, thus making programs easier to read and to modify.easier to read and to modify.Languages with Exception HandlingLanguages with Exception Handling– PLPLI, Mesa, CLU, Eiffel, ML, Ada, C++, and JavaI, Mesa, CLU, Eiffel, ML, Ada, C++, and Java
2626
Design and ImplementationDesign and Implementation
A language might permit the enabling or A language might permit the enabling or disabling of exceptions. disabling of exceptions. After an exception is raised and corresponding After an exception is raised and corresponding exception handler is executed, either control can exception handler is executed, either control can transfer to somewhere in the program outside of transfer to somewhere in the program outside of the handler code, or program execution can the handler code, or program execution can simply be terminated. simply be terminated. This environment under which execution This environment under which execution continues after exception is called the continues after exception is called the continuation of the exceptioncontinuation of the exception..
2727
ContinuationContinuation
Resumption model:Resumption model: – Resume the subprogram execution that Resume the subprogram execution that
invoked the exception. This implementation invoked the exception. This implementation has been adopted by PLhas been adopted by PLI and Mesa. I and Mesa.
Termination model:Termination model: – Terminate the subprogram execution that Terminate the subprogram execution that
invoked the exception and return to the calling invoked the exception and return to the calling environment. Bliss, CLU, ML, and Ada environment. Bliss, CLU, ML, and Ada adopted this simpler scheme. adopted this simpler scheme.
2828Figure 3.1 Exception handling flow of control
© 2003 Brooks/Cole Publishing / Thomson Learning™
2929
Exception Handling in C++Exception Handling in C++
A C++ exception is an instance of an class A C++ exception is an instance of an class (generally an exception class).(generally an exception class).
.... f()f() { throw …;}{ throw …;}.... trytry { f();}{ f();} catch ( …)catch ( …)
3030
Exception Handling in JavaException Handling in Java
A java exception is an instance of a A java exception is an instance of a derived class from the Throwable class.derived class from the Throwable class.
Claiming (throws)Claiming (throws)
Executing (try) Executing (try)
Throwing( throw)Throwing( throw)
Catching (catch)Catching (catch)
3131
Figure 3. 2 Pre-defined exception classes in Java
© 2003 Brooks/Cole Publishing / Thomson Learning™
3232
To be continuedTo be continued
ExpressionsExpressions– FormsForms– EvaluationsEvaluations
Static and Dynamic EnvironmentStatic and Dynamic Environment– The The lifetimelifetime of any data object of any data object– Automatic memory managementAutomatic memory management
3333
ExpressionsExpressions
Expressions are formed from operators Expressions are formed from operators and operands.and operands.
OperatorsOperators are known as functions. are known as functions.
OperandsOperands are known as arguments or are known as arguments or parameters. parameters.
3434
Expression NotationsExpression Notations
Expressions are composed of various Expressions are composed of various fundamental forms:fundamental forms:– InfixInfix– PrefixPrefix– PostfixPostfix– MixfixMixfix
3535
Infix NotationInfix Notation
Operand1 OperatorOperand1 Operator Operand2Operand2
Examples of Infix notation:Examples of Infix notation:1010202040 40 30 30 40 40 1200 12002 2 3 3 5 5 8 8 2 2 15 15 8 8 25 2520 20 10 10 2 2 5 5 12 12
3636
Prefix NotationPrefix Notation
Also known as Also known as PolishPolish the operator appears the operator appears before the operands and has the following before the operands and has the following syntax.syntax.
OperatorOperator Operand1Operand1 Operand2Operand2
Examples in Prefix notation:Examples in Prefix notation: 10 20 40 10 20 40 30 40 30 40 1200 1200 20 20 25 15 25 15 20 40 20 40 800 800 20 10 20 10 2 5 2 5 2 2 2 5 2 5 2 10 2 10 12 12 15 15 2 2 10 8 10 8 2 5 2 5 15 15 2 2 2 10 2 10 15 15 2 2
20 20 15 22 15 22 330 330
3737
Postfix NotationPostfix Notation
Also known as Also known as SuffixSuffix or or Reverse PolishReverse Polish notation,notation,– Operand1Operand1 Operand2Operand2 Operator Operator
Examples in Postfix notation:Examples in Postfix notation:10 20 10 20 40 40 30 40 30 40 1200 120020 25 15 20 25 15 20 40 20 40 800 80020 10 20 10 2 5 2 5 2 2 5 2 2 5 2 10 2 10 12 122 10 8 2 10 8 2 5 2 5 15 15 = 2 2 10 = 2 2 10 15 15 2 2
20 20 15 15 22 15 22 15 330 330
3838
Mixfix NotationMixfix Notation
In In Mixfix notationMixfix notation the operations are the operations are defined as a combination of Prefix, Postfix, defined as a combination of Prefix, Postfix, and Infix notations. For example,and Infix notations. For example,– if conditionif condition thenthen expression1expression1 elseelse
expression2expression2
3939
Examples of Examples of MixfixMixfix
ifif a a b b
thenthen aa2255
elseelse bb3355
whilewhile (a (a b) b)
aabb55
for (afor (a225;5; a a 10; 10;aaaa1)1)
bbbb55
4040
Figure 3.3 Tree representation for expression (5-3)*(2+4)
© 2003 Brooks/Cole Publishing / Thomson Learning™
4141
Figure 3.4 Tree-representation of the express A*B+5*C*D
© 2003 Brooks/Cole Publishing / Thomson Learning™
*
4242
Comparison Comparison
The expression AThe expression ABB55CCD can be D can be represented in Prefix, Postfix, and Infix represented in Prefix, Postfix, and Infix notation as follows. notation as follows.
PrefixPrefix PostfixPostfix InfixInfix
ABAB5CD5CD ABAB5C5CDD AABB55CCDD
4343
Expression EvaluationsExpression Evaluations
Each programming language has rules for Each programming language has rules for the evaluation of expressions.the evaluation of expressions.Here we discuss briefly the fundamental Here we discuss briefly the fundamental kinds of expression evaluations:kinds of expression evaluations:– Applicative orderApplicative order– Normal orderNormal order– Short CircuitShort Circuit– LazyLazy– Block Order.Block Order.
4444
Applicative Order EvaluationApplicative Order Evaluation
SSometimes called ometimes called strict evaluationstrict evaluation or or eager evaluationeager evaluation, , corresponds to a bottom–up evaluation of the values of corresponds to a bottom–up evaluation of the values of nodes of the tree representing an expression. nodes of the tree representing an expression. For example, in the tree representation of the expression For example, in the tree representation of the expression (5(53)3)(2(24), the 4), the and and operators representing the first operators representing the first internal nodes of the tree (bottom–up) are applied to 5 internal nodes of the tree (bottom–up) are applied to 5 and 3 and 2 and 4, respectively, the external nodes, to and 3 and 2 and 4, respectively, the external nodes, to obtain 2 and 6. Then the obtain 2 and 6. Then the operator is used, giving the operator is used, giving the result, 12. result, 12. However, in some languages there is no specific order However, in some languages there is no specific order for the evaluation of operands. for the evaluation of operands.
4545
ExampleExample
An expression 2An expression 2554 can be interpreted 4 can be interpreted alternatively as follows.alternatively as follows.– Perform the multiplication first and addition Perform the multiplication first and addition
next, which produces the value 14.next, which produces the value 14.– Perform the addition first and multiplication Perform the addition first and multiplication
next, which produces the value 18.next, which produces the value 18.
4646
Figure 3.5 Alternative evaluations of the expression 2*5+4
© 2003 Brooks/Cole Publishing / Thomson Learning™
4747
Operator precedence in COperator precedence in COperatorOperator AssociativityAssociativity TypeType( )( ) Left to rightLeft to right ParenthesesParentheses Right to leftRight to left UnaryUnary Left to rightLeft to right MultiplicativeMultiplicative Left to rightLeft to right AdditiveAdditive Left to rightLeft to right RelationalRelational Left to rightLeft to right ShiftShift Left to rightLeft to right EqualityEquality Left to rightLeft to right Bitwise ANDBitwise AND Left to rightLeft to right Bitwise Bitwise exclusive ORexclusive OR Left to rightLeft to right Bitwise ORBitwise OR Left to rightLeft to right Logical ANDLogical AND Left to rightLeft to right Logical ORLogical OR Left to rightLeft to right ConditionalConditional Right to leftRight to left AssignmentAssignment Left to rightLeft to right SequentialSequential
4848
Normal Order EvaluationNormal Order Evaluation
EEvaluate each operand when it is needed in the valuate each operand when it is needed in the computation of the result.computation of the result.For example, consider the following function defined in C For example, consider the following function defined in C when it is called with Add(2when it is called with Add(23).3).Add(X)Add(X)int X;int X;{{ XX X X10;10;}}The result is obtained by substituting the expression 2The result is obtained by substituting the expression 23 3 into X without first evaluating it. Then the expression 2into X without first evaluating it. Then the expression 23 3 is evaluated and used in the function. In other words, is evaluated and used in the function. In other words, 223, not 5, is passed as the value of X to the function.3, not 5, is passed as the value of X to the function.
4949
Short Circuit EvaluationShort Circuit Evaluation
Short circuit evaluationShort circuit evaluation of Boolean, or logical, of Boolean, or logical, expressions corresponds to evaluation of an expression expressions corresponds to evaluation of an expression without evaluating all its sub expressions.without evaluating all its sub expressions.For example, the Boolean expressionFor example, the Boolean expression X or TrueX or Trueandand
True or X True or X are true regardless of whether X is true or false. are true regardless of whether X is true or false. Similarly,Similarly, False and XFalse and Xis evaluated as false with regard to any value for X.is evaluated as false with regard to any value for X.
5050
Short Circuits of JavaShort Circuits of Java
boolean b, c, d; boolean b, c, d; b = !(3 > 2); // b is false b = !(3 > 2); // b is false c = !(2 > 3); // c is true c = !(2 > 3); // c is true d = b && c; // d is false d = b && c; // d is false d = b && c;d = b && c;– //false regardless of c, so Java doesn't bother //false regardless of c, so Java doesn't bother
checking the value of c. checking the value of c.
How about?How about?– boolean b = (n == 0) || (m/n > 2); boolean b = (n == 0) || (m/n > 2);
5151
Lazy EvaluationLazy Evaluation
Sometimes called Sometimes called delayed evaluationdelayed evaluation. . It eliminates unnecessary evaluation of expressions It eliminates unnecessary evaluation of expressions resulting:resulting:– Postponing evaluation of an expression until it is needed.Postponing evaluation of an expression until it is needed.– Eliminating the reevaluation of the same expression more than Eliminating the reevaluation of the same expression more than
once.once.
It is not evaluated until its value is required and, once It is not evaluated until its value is required and, once evaluated, is never reevaluated. evaluated, is never reevaluated. The conditional statements suggest the use of lazy The conditional statements suggest the use of lazy evaluation, indicating that never evaluate operands before evaluation, indicating that never evaluate operands before applying the operation; instead, always pass the operands applying the operation; instead, always pass the operands unevaluated and let the operation decides if evaluation is unevaluated and let the operation decides if evaluation is needed. The best example is the case of expressions needed. The best example is the case of expressions containing conditionals. containing conditionals.
5252
ExampleExample
The C expressionThe C expressionZ Z (Y (Y 0 ? X : X 0 ? X : X Y) Y)has an embedded if statement that computes Xhas an embedded if statement that computes XY if Y is Y if Y is not 0. But, if we evaluate the operands of the conditional not 0. But, if we evaluate the operands of the conditional operator, we produce the effect of doing exactly what the operator, we produce the effect of doing exactly what the conditional statement is set up to avoid, meaning that conditional statement is set up to avoid, meaning that dividing X by Y even if Y is zero. Clearly, in this case we dividing X by Y even if Y is zero. Clearly, in this case we are not interested all the operands to be evaluated are not interested all the operands to be evaluated before the operation is applied. Instead, we need to pass before the operation is applied. Instead, we need to pass the operands to the conditional operation unevaluated the operands to the conditional operation unevaluated and let the operation determine the order of evaluation. and let the operation determine the order of evaluation.
5353
Block Order EvaluationBlock Order EvaluationEEvaluate an expression containing a declaration. valuate an expression containing a declaration. For example, in Pascal a block expression is a function For example, in Pascal a block expression is a function body involving variable declaration. body involving variable declaration. In ML "let In ML "let declarationdeclaration in in expressionexpression end" forms a block end" forms a block expression, where the sub-expression is evaluated and the expression, where the sub-expression is evaluated and the bindings produced by bindings produced by declarationdeclaration are used for evaluating are used for evaluating expressionexpression. . For example, For example, – letlet valval SS(X(XYYZ) Z) 0.5 0.5– inin sqrt (S sqrt (S (S(SX) X) (S (SY) Y) (S (SZ))Z))– endend
In this form the entire let-end is an expression, or its body, In this form the entire let-end is an expression, or its body, indicating that expressions may be nested. indicating that expressions may be nested. In Smalltalk, there is such block expression.In Smalltalk, there is such block expression.– a = [x: y:| ^(x+y).].a = [x: y:| ^(x+y).].– a value: 5 value: 6.a value: 5 value: 6.
5454
Static and Dynamic Static and Dynamic EnvironmentsEnvironments
The The lifetimelifetime of any data object begins when the binding of of any data object begins when the binding of the data object to a particular storage location is made.the data object to a particular storage location is made.The lifetime of data object ends when this binding of The lifetime of data object ends when this binding of object to storage block is dissolved. When a data object object to storage block is dissolved. When a data object is created an is created an access pathaccess path to the data object must also be to the data object must also be created so that the data object can be accessed by created so that the data object can be accessed by operations in the program execution.operations in the program execution.Creation of an access path can be accomplished in two Creation of an access path can be accomplished in two ways:ways:– Through association of the data object with a name.Through association of the data object with a name.– Through association of the data object with a pointer.Through association of the data object with a pointer.
At the end of the lifetime of the data object, this block of At the end of the lifetime of the data object, this block of storage must be recovered for reallocation to another data storage must be recovered for reallocation to another data object at some later time. object at some later time.
5555
Figure 3.6 General form of an activation record
© 2003 Brooks/Cole Publishing / Thomson Learning™
5656
Automatic memory managementAutomatic memory managementIn procedural languages, the dynamic allocation and In procedural languages, the dynamic allocation and deallocation of storage occurs only for stack-based access deallocation of storage occurs only for stack-based access operations (PUSH and POP).operations (PUSH and POP).This is a relatively easy implementation, in which storage is This is a relatively easy implementation, in which storage is allocated for the stack when a procedure is called and allocated for the stack when a procedure is called and deallocated when the procedure is exited.deallocated when the procedure is exited.Pointers are particularly interested in procedural languages, Pointers are particularly interested in procedural languages, in which they provide a means of dynamic memory allocation in which they provide a means of dynamic memory allocation from a special area of storage called the from a special area of storage called the heapheap. . Examples are Examples are newnew and and disposedispose in Pascal and in Pascal and mallocmalloc and and freefree in C for allocation and deallocation of storage, in C for allocation and deallocation of storage, respectively.respectively.Automatic memory management actually falls into two Automatic memory management actually falls into two categories: categories: – Maintaining Free SpaceMaintaining Free Space– Garbage CollectionGarbage Collection
5757
Maintaining Free SpaceMaintaining Free SpaceThis is the process of maintaining the free space This is the process of maintaining the free space available for allocation.available for allocation.A contiguous block of memory is provided by the A contiguous block of memory is provided by the operating system for the use of an executing operating system for the use of an executing program.program.The free space within this block is maintained by The free space within this block is maintained by a list of free blocks. One way to do this is via a a list of free blocks. One way to do this is via a linked-list. linked-list. In general, compaction involves considerable In general, compaction involves considerable overhead, since the locations of most of the overhead, since the locations of most of the allocated blocks will change and data structures allocated blocks will change and data structures and tables in the runtime environment will have to and tables in the runtime environment will have to be modified to reflect these new locations. be modified to reflect these new locations.
5858
Garbage and Garbage Garbage and Garbage CollectionsCollections
This process sometimes called This process sometimes called Reclamation of Reclamation of StorageStorage reclaims storage allocated but no reclaims storage allocated but no longer used.longer used.An alternative heap management approach is An alternative heap management approach is garbage collectiongarbage collection, which keeps track of , which keeps track of allocated but inaccessible storage called allocated but inaccessible storage called garbagegarbage, and permits it to be reallocated., and permits it to be reallocated.GarbageGarbage– When all access paths to a data object are destroyed When all access paths to a data object are destroyed
but the data object continues to exist, the data object but the data object continues to exist, the data object is said to be is said to be garbagegarbage. .
5959
Figure 3.7 Allocated space to an executing program
© 2003 Brooks/Cole Publishing / Thomson Learning™
Figure 3.8 New block allocated to an executing program
© 2003 Brooks/Cole Publishing / Thomson Learning™
6060
Figure 3.9 Reclaiming blocks allocated to an executing program
© 2003 Brooks/Cole Publishing / Thomson Learning™
Figure 3.10 Coalescing free blocks into one large block
© 2003 Brooks/Cole Publishing / Thomson Learning™
6161
Dangling ReferencesDangling ReferencesWhen an access path continues to exist after the lifetime of the associated When an access path continues to exist after the lifetime of the associated data object, the data object is said to be data object, the data object is said to be dangling referencedangling reference. . Consider the following code in C language, in which X and Y as two pointer Consider the following code in C language, in which X and Y as two pointer variables, are pointing to different memory locations: variables, are pointing to different memory locations:
int int X, X, Y;Y;X X new int; new int;Y Y new int; new int;
The following statementThe following statementX X Y; Y;
leaves X and Y pointing to the same storage. In this situation, the storage that leaves X and Y pointing to the same storage. In this situation, the storage that X was pointing to is still allocated in the program execution environment, but it X was pointing to is still allocated in the program execution environment, but it is inaccessible, thus there is a garbage produced associated with A location. is inaccessible, thus there is a garbage produced associated with A location. Consequently, in this situation, the statementConsequently, in this situation, the statement
free(X);free(X);deallocates the storage that X points to, leaves X as dangling reference, it deallocates the storage that X points to, leaves X as dangling reference, it also leaves Y as dangling reference, since they were both pointing to the also leaves Y as dangling reference, since they were both pointing to the same storage.same storage.
6262
Figure 3.11 Dynamic memory allocation can result in garbage and dangling references
© 2003 Brooks/Cole Publishing / Thomson Learning™
6363
Dangling referenceDangling reference
Dynamic memory allocation can result to garbage and In Dynamic memory allocation can result to garbage and In the following code in C language when function Add is the following code in C language when function Add is exited, the pointer variable X is deallocated and the exited, the pointer variable X is deallocated and the memory allocated to X is no longer accessible by the memory allocated to X is no longer accessible by the program outside of the function, indicating that the program outside of the function, indicating that the memory allocated to X is garbage. memory allocated to X is garbage.
Add ( )Add ( ){{
int int X;X;X X (int *) malloc (sizeof (int) ); (int *) malloc (sizeof (int) );
. . . . . .
. . . . . .
}}
6464
Mark-Scan MethodMark-Scan Method
In this method sometime called In this method sometime called Mark-SweepMark-Sweep, each node , each node of the graph represented by the program execution must of the graph represented by the program execution must contain an extra bit for marking. This method runs contain an extra bit for marking. This method runs automatically when storage is about to run out and automatically when storage is about to run out and consists of two phases:consists of two phases:– Mark phase:Mark phase: During the During the markmark phase, the entire graph associated phase, the entire graph associated
with program execution is examined, marking each storage that with program execution is examined, marking each storage that is encountered, thus a storage remains unmarked if it is not is encountered, thus a storage remains unmarked if it is not referenced in program execution. In other words, in referenced in program execution. In other words, in markmark phase, phase, the garbage collector identifies all of those storage that are the garbage collector identifies all of those storage that are accessible, that is, that are not garbage.accessible, that is, that are not garbage.
– Scan phase:Scan phase: The entire graph is checked and all unmarked The entire graph is checked and all unmarked storage are returned to heap, indicating that unreferenced storage are returned to heap, indicating that unreferenced storage are garbage and are reclaimed. In other words, in scan storage are garbage and are reclaimed. In other words, in scan phase, the garbage collector places all of the inaccessible phase, the garbage collector places all of the inaccessible storage in the free storage area, often by placing them on the storage in the free storage area, often by placing them on the free-list.free-list.
6565
Figure 3.12 Example of the mark phase of garbage collection© 2003 Brooks/Cole Publishing / Thomson Learning™
C
F
6666
Copying MethodCopying Method
In copying method, the available memory is In copying method, the available memory is divided into two sections:divided into two sections:– From-space:From-space: Memory is allocated to a running Memory is allocated to a running
program.program.– To-space:To-space: When the copying method is invoked. When the copying method is invoked.– In this method, the entire structure is examined, in In this method, the entire structure is examined, in
which each storage is copied from from-space to to-which each storage is copied from from-space to to-space. What is inaccessible remains in from-space space. What is inaccessible remains in from-space and is thus garbage. When the copying is finished, and is thus garbage. When the copying is finished, from-space and to-space are exchanged. from-space and to-space are exchanged.
6767
Reference-Counting methodReference-Counting method
This method requires an extra filed in each node This method requires an extra filed in each node of the graph structure represented by the of the graph structure represented by the program execution to count references to the program execution to count references to the node. In this method, when a node is created, node. In this method, when a node is created, the count is set to 1.the count is set to 1.– Count-increment:Count-increment: If the node is referenced count is If the node is referenced count is
increased by 1.increased by 1.– Count-decrement:Count-decrement: If the node is not referenced If the node is not referenced
count is decreased by 1. count is decreased by 1.
Consequently, when the count is set to 0, the Consequently, when the count is set to 0, the memory of the node is returned to available memory of the node is returned to available storage pool. storage pool.
6868
SummarySummary
AbstractionAbstraction
Parameters and Parameters TransmissionParameters and Parameters Transmission
Exception and Exception HandlingException and Exception Handling
ExpressionsExpressions
Static and Dynamic EnvironmentStatic and Dynamic Environment