Download presentation
Presentation is loading. Please wait.
1
Chapter 6 Data Types
2
Chapter 6 Topics Introduction Primitive Data Types
Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer Types
3
Introduction A data type defines a collection of data objects and a set of predefined operations on those objects Evolution of data types: FORTRAN I (1957) - INTEGER, REAL, arrays Ada (1983) - User can create a unique type for every category of variables in the problem space and have the system enforce the types Definition: A descriptor is the collection of the attributes of a variable
4
Orthogonality ORTHOGONALITY is a useful goal in the design of a language, particularly its type system A collection of features is orthogonal if there are no restrictions on the ways in which the features can be combined (analogy to vectors) struct T1 { int ar1[20]; float x; }; struct T1 arr2[30]; Eg. Struct of array, array of struct, array of array ,…
5
Type System Definition
A TYPE SYSTEM has rules for type equivalence (when are the types of two values the same?): int x,y; type compatibility (when can a value of type A be used in a context that expects type B?) x+y if x is int but y is real. type inference (what is the type of an expression, given the types of the operands?) … see more in expression. What is the type of (x+y) ?
6
Type Conversion Coercion: Automatic type conversion
When an expression of one type is used in a context where a different type is expected, one normally gets a type error But what about var a : integer; b, c : real; c := a + b;
7
Type Conversion C has lots of coercion, too, but with simpler rules:
all floats in expressions become doubles short int and char become int in expressions if necessary, precision is removed when assigning into LHS
8
Type Checking In effect, coercion rules are a relaxation of type checking Recent thought is that this is probably a bad idea Languages such as Modula-2 and Ada do not permit coercions C++, however, goes hog-wild with them They're one of the hardest parts of the language to understand
9
Type Checking Make sure you understand the difference between
type conversions (explicit) type coercions (implicit) sometimes the word 'cast' is used for conversions (C is guilty here)
10
Introduction Design issues for all data types:
1. What is the syntax of references to variables? 2. What operations are defined and how are they specified?
11
Primitive Data Types Those not defined in terms of other data types
1. 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
12
Primitive Data Types 2. Floating Point
Model real numbers, but only as approximations Languages for scientific use support at least two floating-point types; sometimes more Usually exactly like the hardware, but not always
13
IEEE Floating Point Formats
14
Primitive Data Types 3. Decimal For business applications (money)
Store a fixed number of decimal digits (coded) Advantage: accuracy Disadvantages: limited range, wastes memory Consider: Cobol, Excel, VB, reports/forms tools
15
Primitive Data Types 4. Boolean 5. Character
Could be implemented as bits, but often as bytes Advantage: readability 5. Character Stored as numeric codings (e.g., ASCII, Unicode, UTF)
16
Character String Types
Values are sequences of characters Design issues: 1. Is it a primitive type or just a special kind of array? 2. Is the length of objects static or dynamic?
17
Character String Types
Operations: Assignment Comparison (=, >, etc.) Catenation Substring reference Pattern matching
18
Character String Types
Examples: Pascal Not primitive; assignment and comparison only (of packed arrays) Ada, FORTRAN 90, and BASIC Somewhat primitive Assignment, comparison, catenation, substring reference FORTRAN has an intrinsic for pattern matching e.g. (Ada) N := N1 & N2 (catenation) N(2..4) (substring reference)
19
Character String Types
C and C++ Not primitive Use char arrays and a library of functions that provide operations
20
Character String Types
Perl and JavaScript, PHP Patterns are defined in terms of regular expressions A very powerful facility e.g., /[A-Za-z][A-Za-z\d]+/ Java - String class (not arrays of char) Objects cannot be changed (immutable) StringBuffer is a class for changeable string objects
21
Character String Types
String Length Options: 1. Static - FORTRAN 77, Ada, COBOL e.g. (FORTRAN 90) CHARACTER (LEN = 15) NAME; 2. Limited Dynamic Length - C and C++ actual length is indicated by a null character. 3. Dynamic - SNOBOL4, Perl, JavaScript
22
Character String Types
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?
23
Character String Types
Implementation: Static length - compile-time descriptor Limited dynamic length - may need a run-time descriptor for length (but not in C and C++) Dynamic length - need run-time descriptor; allocation/deallocation is the biggest implementation problem
24
Character String Types
Compile-time descriptor for static strings Run-time descriptor for limited dynamic strings
25
User-Defined Ordinal Types
An ordinal type is one in which the range of possible values can be easily associated with the set of positive integers
26
User-Defined Ordinal Types
1. Enumeration Types - one in which the user enumerates all of the possible values, which are symbolic constants Design Issue: Should a symbolic constant be allowed to be in more than one type definition? enum color {red, green,blue} enum set1 {red, green, blue}; enum set2{ red, purple, pink};
27
User-Defined Ordinal Types
Examples: Pascal - cannot reuse constants; they can be used for array subscripts, for variables, case selectors; NO input or output; can be compared Ada - constants can be reused (overloaded literals); distinguish with context or type_name ‘ (one of them); can be used as in Pascal; CAN be input and output C and C++ - like Pascal, except they can be input and output as integers Java does not include an enumeration type, but provides the Enumeration interface
28
Example enum mycolor {red,green,blue} : main() { enum mycolor c1; Type
int a[c1]; // **wrong scanf("%d", &c1); //**ok as integer switch (c1) { case red: ... case green: ... } Type mycolor = {red,green,blue}; Var c1 : mycolor; a : array [mycolor] of integer; : begin {main} readln(c1); {** cannot do**} writeln(c1); { ** cannot do **} for c1 = green to blue do begin a[c1] = a[c1] + 2 end end{main}
29
User-Defined Ordinal Types
Evaluation (of enumeration types): a. Aid to readability--e.g. no need to code a color as a number b. Aid to reliability--e.g. compiler can check: i. operations (don’t allow colors to be added) ii. ranges of values (if you allow 7 colors and code them as the integers, 1..7, then 9 will be a legal integer (and thus a legal color)) #define RED 0 #define GREEN 1 int c; c = 1; if (c==GREEN) ... enum color {red,green} c; c = red; if (c==green) .. if (c > 1) printf(“value error”);
30
User-Defined Ordinal Types
2. Subrange Type An ordered contiguous subsequence of an ordinal type Design Issue: How can they be used? TYPE mysmallint = [1..10]; mycolor1 = [red..blue];
31
User-Defined Ordinal Types
Examples: Pascal - Subrange types behave as their parent types; can be used as for variables and array indices e.g. type pos = 0 .. MAXINT; for i= red to blue A[i] := …. i:mycolor1; A:array [mycolor1] of integer;
32
User-Defined Ordinal Types
Examples of Subrange Types (continued) Ada - Subtypes are not new types, just constrained existing types (so they are compatible); can be used as in Pascal, plus case constants e.g. subtype POS_TYPE is INTEGER range 0..INTEGER'LAST; contrained integer
33
User-Defined Ordinal Types
Evaluation of subrange types: Aid to readability Reliability - restricted ranges add error detection
34
User-Defined Ordinal Types
Implementation of user-defined ordinal types Enumeration types are implemented as integers Subrange types are the parent types with code inserted (by the compiler) to restrict assignments to subrange variables TYPE sub1 = [1..10];
35
Arrays 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.
36
Arrays Design Issues: 1. What types are legal for subscripts?
2. Are subscripting expressions in element references range checked? 3. When are subscript ranges bound? 4. When does allocation take place? 5. What is the maximum number of subscripts? 6. Can array objects be initialized? 7. Are any kind of slices allowed?
37
Arrays Indexing is a mapping from indices to elements
map(array_name, index_value_list) an element e.g. map (array,i) array[i] Index Syntax FORTRAN, PL/I, Ada use parentheses Most other languages use brackets
38
Arrays Subscript Types: FORTRAN, C - integer only
Pascal - any ordinal type (integer, boolean, char, enum) Ada - integer or enum (includes boolean and char) Java - integer types only
39
Arrays Categories of arrays (based on subscript binding and binding to storage) 1. Static - range of subscripts and storage bindings are static e.g. FORTRAN 77, some arrays in Ada Advantage: execution efficiency (no allocation or deallocation) int a[10][10]; main() { }
40
Arrays 2. Fixed stack dynamic - range of subscripts is statically bound, but storage is bound at elaboration time e.g. Most Java locals, and C locals that are not static Advantage: space efficiency int f() { int a[10]; // stack dynamic only array }
41
Arrays 3. Stack-dynamic - range and storage are dynamic, but fixed from then on for the variable’s lifetime e.g. Ada declare blocks declare STUFF : array (1..N) of FLOAT; begin ... end; Advantage: flexibility - size need not be known until the array is about to be used int f( int len1,len2) { int a[len1][len2]; // stack dynamic both subscript and array }
42
Arrays 4. Heap-dynamic - subscript range and storage bindings are dynamic and not fixed e.g. (FORTRAN 90) INTEGER, ALLOCATABLE, ARRAY (:,:) :: MAT (Declares MAT to be a dynamic 2-dim array) ALLOCATE (MAT (10,NUMBER_OF_COLS)) (Allocates MAT to have 10 rows and NUMBER_OF_COLS columns) DEALLOCATE MAT (Deallocates MAT’s storage)
43
Arrays 4. Heap-dynamic (continued)
In APL, Perl, and JavaScript, arrays grow and shrink as needed In Java, all arrays are objects (heap-dynamic)
44
Arrays int f( int len) { int m[len][len]; // stack dynamic both
//subscript and array }
45
Arrays Number of subscripts Array Initialization
FORTRAN I allowed up to three FORTRAN 77 allows up to seven Others - no limit Array Initialization Usually just a list of values that are put in the array in the order in which the array elements are stored in memory
46
Arrays Examples of array initialization:
1. FORTRAN - uses the DATA statement, or put the values in / ... / on the declaration 2. C and C++ - put the values in braces; can let the compiler count them e.g. int stuff [] = {2, 4, 6, 8}; int stuff2[] = {2,4,5,7}; // error int stuff3[][2] = {2,3,4,5}; // ok
47
Arrays Examples of array initialization:
3. Ada - positions for the values can be specified e.g. SCORE : array (1..12, 1..30) := (1 => (24, 10), 2 => (10, 7), 3 =>(12, 30), others => (0, 0)); 4. Pascal does not allow array initialization Position 1 contains score value 24,10.
48
Arrays Array Operations 1. APL - many, see book (p. 240-241) 2. Ada
Assignment; RHS can be an aggregate constant or an array name Catenation; for all single-dimensioned arrays Relational operators (= and /= only) 3. FORTRAN 90 Intrinsics (subprograms) for a wide variety of array operations (e.g., matrix multiplication, vector dot product)
49
Compile-Time Descriptors
Single-dimensioned array Multi-dimensional array
50
Arrays Slices A slice is some substructure of an array; nothing more than a referencing mechanism Slices are only useful in languages that have array operations
51
Arrays Slice Examples: INTEGER MAT (1:4, 1:4)
1. FORTRAN 90 INTEGER MAT (1:4, 1:4) MAT(1:4, 1) - the first column MAT(2, 1:4) - the second row
52
Example Slices in FORTRAN 90
53
Arrays
54
Arrays Slice Examples: 2. Ada - single-dimensioned arrays only
LIST(4..10)
55
Arrays Implementation of Arrays
maps subscript expressions to an address in the array Row major (by rows) or column major order (by columns)
56
Arrays A[i,j] Row .. Row 1 Row 2 A[i,j] Col .. Col 1 Col 2
57
Arrays
58
Locating an Element A A[i][j] Columnwise Rowwise
address of A+ (m*(j-1) + i-1 )* size of element address of A+ (n*(i-1) + j-1 )* size of element
59
Arrays Two layout strategies for arrays (Figure 7.10):
Contiguous elements Row pointers an option in C allows rows to be put anywhere - nice for big arrays on machines with segmentation problems avoids multiplication nice for matrices whose rows are of different lengths e.g. an array of strings requires extra space for the pointers
60
Arrays
61
Arrays Example: Suppose
A : array [L1..U1] of array [L2..U2] of array [L3..U3] of elem; D1 = U1-L1+1 D2 = U2-L2+1 D3 = U3-L Let S3 = size of elem S2 = D3 * S3 S1 = D2 * S2
62
Arrays
63
Arrays Example (continued)
We could compute all that at run time, but we can make do with fewer subtractions: == (i * S1) + (j * S2) + (k * S3) + address of A - [(L1 * S1) + (L2 * S2) + (L3 * S3)] The stuff in square brackets is compile-time constant that depends only on the type of A
64
Dynamic Memory Allocation for the One-Dimensional Array A
Example of an array allocation.
65
Dynamic Memory Allocation Memory Allocation for
Two-Dimensional Array C Example of an array allocation.
66
Associative Arrays An associative array is an unordered collection of data elements that are indexed by an equal number of values called keys Design Issues: 1. What is the form of references to elements? 2. Is the size static or dynamic?
67
Associative Arrays Structure and Operations in Perl Names begin with %
Literals are delimited by parentheses e.g., %hi_temps = ("Monday" => 77, "Tuesday" => 79,…); Subscripting is done using braces and keys $hi_temps{"Wednesday"} = 83; Elements can be removed with delete delete $hi_temps{"Tuesday"};
68
Records A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names Design Issues: 1. What is the form of references? 2. What unit operations are defined?
69
Records Record Definition Syntax Record Field References
COBOL uses level numbers to show nested records; others use recursive definition Record Field References 1. COBOL field_name OF record_name_1 OF ... OF record_name_n 2. Others (dot notation) record_name_1.record_name_ record_name_n.field_name
70
Records Fully qualified references must include all record names
Elliptical references allow leaving out record names as long as the reference is unambiguous Pascal provides a with clause to abbreviate references
71
TYPE studentinfo = record id : integer; name : packed array[1..20] of char; end; VAR myrec : studentinfo; begin ... with myrec do begin id = 1; name = 'abc'; end end. struct studentinfo { int id; char name[20]; } myrec; .. myrec.id = 1; strcpy(&myrec.name,"abc");
72
Records A compile-time descriptor for a record
73
Records Record Operations 1. Assignment
Pascal, Ada, and C allow it if the types are identical (by structure) In Ada, the RHS can be an aggregate constant 2. Initialization Allowed in Ada, using an aggregate constant
74
Records Record Operations (continued) 3. Comparison
In Ada, = and /=; one operand can be an aggregate constant 4. MOVE CORRESPONDING In COBOL - it moves all fields in the source record to fields with the same names in the destination record if x=y then
75
The statement 'MOVE CORRESPONDING GROUP-1 TO GROUP-2' will cause both FIELD-A and FIELD-E to be moved. FIELD-C and FIELD-D have different group-level names so they don't correspond.
76
Records Comparing records and arrays
1. Access to array elements is much slower than access to record fields, because subscripts are dynamic (field names are static) 2. Dynamic subscripts could be used with record field access, but it would disallow type checking and it would be much slower
77
Sample Structure Representing an Individual Employee (Dynamic)
struct studentinfo { int id; char name[20]; } myrec; void f() { struct studentinfo *s1; s1 = (struct studentinfo *) malloc(sizeof (struct studentinfo)); ... }
78
Unions A union is a type whose variables are allowed to store different type values at different times during execution Design Issues for unions: 1. What kind of type checking, if any, must be done? 2. Should unions be integrated with records?
79
Unions Examples: e.g. type intreal = record tagg : Boolean of
1. FORTRAN - with EQUIVALENCE No type checking 2. Pascal - both discriminated and nondiscriminated unions e.g. type intreal = record tagg : Boolean of true : (blint : integer); false : (blreal : real); end; Problem with Pascal’s design: type checking is ineffective
80
Unions A discriminated union of three shape variables struct shape {
enum filled {yes,no} filled; enum color {red, green, blue) color; enum form {circle, rectangle,triangle} discrimant; union { float diameter; struct { float side1,side2; } s; struct { float leftside,rightside,angle;} t; } property; } Unions A discriminated union of three shape variables
81
Unions Reasons why Pascal’s unions cannot be type checked effectively:
a. User can create inconsistent unions (because the tag can be individually assigned) var blurb : intreal; x : real; blurb.tagg := true; { it is an integer } blurb.blint := 47; { ok } blurb.tagg := false; { it is a real } x := blurb.blreal; { assigns an integer to real }
82
Unions Reasons why Pascal’s unions cannot be type checked effectively (continued): b. The tag is optional! Now, only the declaration and the second and last assignments are required to cause trouble
83
Unions Examples (continued): 3. Ada - discriminated unions
Reasons they are safer than Pascal: a. Tag must be present b. It is impossible for the user to create an inconsistent union (because tag cannot be assigned by itself--All assignments to the union must include the tag value, because they are aggregate values)
84
Unions Examples (continued):
union myu{ int x; float y; } m1; Unions Examples (continued): 5. C and C++ - free unions (no tags) Not part of their records No type checking of references 6. Java has neither records nor unions Evaluation - potentially unsafe in most languages (not Ada) int float
85
Structure VS Union Memory layout and its impact (structures)
32-bit bus CPU struct myrec { char name[2]; float atomic_number; // 4 bytes for float double atomic_weight; // 8 bytes for double bool metalic; } 1 bus cycle Per word
86
Structure VS Union Memory layout and its impact (structures) 31 1000
1000 R1 …0… LLH R1, [1000] ; we load lower half word of the whole word LUH R2, [1004]; load upper half word of the whole word SHL R2,16 ; shift R2 to upper 16 bits OR R3,R1,R2 OR …0… R2 R3
87
Structure VS Union Memory layout and its impact (structures)
What are assembly instructions required?
88
Structure VS Union Memory layout and its impact (unions)
89
Structure VS Union Memory layout and its impact (unions)
90
Sets A set is a type whose variables can store unordered collections of distinct values from some ordinal type Design Issue: What is the maximum number of elements in any set base type?
91
Lists A list is defined recursively as either the empty list or a pair consisting of an object (which may be either a list or an atom) and another (shorter) list Lists are ideally suited to programming in functional and logic languages In Lisp, in fact, a program is a list, and can extend itself at run time by constructing a list and executing it Lists can also be used in imperative programs
92
Pointers And Recursive Types
Pointers serve two purposes: efficient (and sometimes intuitive) access to elaborated objects (as in C) dynamic creation of linked data structures, in conjunction with a heap storage manager Several languages (e.g. Pascal) restrict pointers to accessing things in the heap Pointers are used with a value model of variables They aren't needed with a reference model
93
Pointers And Recursive Types
(r,((x), (y,(z,(w)))) )
94
Pointers And Recursive Types
C pointers and arrays int *a == int a[] int **a == int *a[] BUT equivalences don't always hold Specifically, a declaration allocates an array if it specifies a size for the first dimension otherwise it allocates a pointer int **a, int *a[] pointer to pointer to int int *a[n], n-element array of row pointers int a[n][m], 2-d array
95
Pointers And Recursive Types
Compiler has to be able to tell the size of the things to which you point So the following aren't valid: int a[][] bad int (*a)[] bad C declaration rule: read right as far as you can (subject to parentheses), then left, then out a level and repeat int *a[n], n-element array of pointers to integer int (*a)[n], pointer to n-element array of integers
96
Pointers Problems with pointers: 1. Dangling pointers (dangerous)
A pointer points to a heap-dynamic variable that has been deallocated Creating one (with explicit deallocation): a. Allocate a heap-dynamic variable and set a pointer to point at it b. Set a second pointer to the value of the first pointer c. Deallocate the heap-dynamic variable, using the first pointer
97
Pointers Problems with pointers (continued):
2. Lost Heap-Dynamic Variables ( wasteful) A heap-dynamic variable that is no longer referenced by any program pointer Creating one: a. Pointer p1 is set to point to a newly created heap-dynamic variable b. p1 is later set to point to another newly created heap-dynamic variable The process of losing heap-dynamic variables is called memory leakage
98
Pointers Examples (continued): 3. C and C++
Used for dynamic storage management and addressing Explicit dereferencing and address-of operator Domain type need not be fixed (void *) void * - Can point to any type and can be type checked (cannot be dereferenced) void *t; t = (void *) malloc(20); char *x; x =(char *) t;
99
Pointers float stuff[100]; float *p; p = stuff;
3. C and C++ (continued) Can do address arithmetic in restricted forms, e.g.: 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] (Implicit scaling)
100
Pointers Examples (continued): 4. FORTRAN 90 Pointers
Can point to heap and non-heap variables Implicit dereferencing Pointers can only point to variables that have the TARGET attribute The TARGET attribute is assigned in the declaration, as in: INTEGER, TARGET :: NODE
101
Pointers Examples (continued): 5. C++ Reference Types
Constant pointers that are implicitly dereferenced Used for parameters Advantages of both pass-by-reference and pass-by-value f(int & x) { .. x=10; } f(a); f(int * x) { .. *x=10; } f(&a);
102
Pointers Examples (continued): 6. Java - Only references
No pointer arithmetic Can only point at objects (which are all on the heap) No explicit deallocator (garbage collection is used) Means there can be no dangling references Dereferencing is always implicit
103
Pointers Evaluation of pointers:
1. Dangling pointers and dangling objects are problems, as is heap management 2. Pointers are like goto's--they widen the range of cells that can be accessed by a variable 3. Pointers or references are necessary for dynamic data structures--so we can't design a language without them
104
Pointers Representation of pointers and references
Large computers use single values Intel microprocessors use segment and offset Dangling pointer problem 1. Tombstone: extra heap cell that is a pointer to the heap-dynamic variable The actual pointer variable points only at tombstones When heap-dynamic variable deallocated, tombstone remains but set to nil
105
Implementing Dynamic Variables
106
Tombstones
107
Tombstones 20 t1 char *t1, *t2,*t3,*t4,*t5;
t1 = (char*) malloc (20*sizeof (char)); t2 = (char*) malloc (30*sizeof (char)); t3 =(char*) malloc (40*sizeof (char)); t4=t3; t5=t2; 30 t2 t5 40 t3 t4
108
Tombstones char *t1, *t2,*t3,*t4,*t5; t1 = (char*) malloc (20*sizeof (char)); t2 = (char*) malloc (30*sizeof (char)); t3 =(char*) malloc (40*sizeof (char)); t4=t3; t5=t2; 20 t1 30 t2 t5 40 t3 t4 How many bytes are needed for tombstone nodes here? (1 pointer = 2 bytes);
109
Pointers Dangling pointer problem (continued)
2. Locks and keys: Pointer values are represented as (key, address) pairs Heap-dynamic variables are represented as variable plus cell for integer lock value When heap-dynamic variable allocated, lock value is created and placed in lock cell and key cell of pointer
110
Locks and Keys
111
Lock and Key t1 20 30 char *t1, *t2,*t3,*t4,*t5; t1 = (char*) malloc (20*sizeof (char)); t2 = (char*) malloc (30*sizeof (char)); t3 =(char*) malloc (40*sizeof (char)); t4=t3; t5=t2; t2 t5 40 t3 t4 How many bytes are needed for space for lock-and-key overhead here? (1 int = 1 byte);
112
Pointers Heap management overview
Single-size cells vs. variable-size cells Reference counters (eager approach) vs. garbage collection (lazy approach) 1. Reference counters: maintain a counter in every cell that store the number of pointers currently pointing at the cell Disadvantages: space required, execution time required, complications for cells connected circularly
113
Pointers Heap management
2. Garbage collection: allocate and disconnect until all available cells allocated; then begin gathering all garbage Every heap cell has an extra bit used by collection algorithm All cells initially set to garbage All pointers traced into heap, and reachable cells marked as not garbage All garbage cells returned to list of available cells
114
Pointers Heap management (continued)
2. Garbage collection (continued): Disadvantages: when you need it most, it works worst (takes most time when program needs most of cells in heap)
115
Marking Style Algorithm
116
Garbage Collection P= free(p); q=p p=new node(); q=new node();
Dangling pointer Lost heap
117
The New (5) Heap Allocation Function Call: Before and After
Unused cells may not be contiguous. 5 pieces of cells are allocated
118
Garbage Collection
119
Garbage Collection p q q Check how RCs are changed.
120
Garbage Collection p 2 3 1 1 2 1 q 1 q Check how RCs are changed.
121
Garbage Collection Implementation: Use freelist Each node has RC.
To allocate memory, get node from freelist and set its RC=1. When performing p=q, decrement RC of nodes pointed by p by one, and increment RC of nodes pointed by q by one.
122
Garbage Collection Basic problem is
Note that node can be returned to freelist only when its RC = 0. Advantage: easy, and dynamic. Disadvantage: RC space overhead, the above problem.
123
Garbage Collection Mark and Sweep
Offline algorithm: only invoked when freelist is empty. Once activated, may take long time clear up. Need one bit for marking
124
Garbage Collection Mark and Sweep Two phases:
Mark: traverse all memory cell from active pointer variables and by chaining and mark their bits as accessible. Sweep: Scan all memory region, to free up all unmark cells.
125
Garbage Collection When called It performs
To clean up when freelist = NULL.
126
Garbage Collection When called It performs 1 1 What is this ? 1 1
Initial memory configuration
127
Garbage Collection When called It performs After pass 1 of mark-sweep.
128
Garbage Collection Assume memory configuration
129
Garbage Collection
130
Garbage Collection When called It performs After pass 2 of mark-sweep.
131
Garbage Collection Copy collection
Heap is divided into two equal blocks: from_space, to_space freelist points to the next available block in from_space. Initialization: from_space to_space
132
Garbage Collection Copy collection When we allocate memory,
// If we use more than half. // after flipping //still over the half.
133
Garbage Collection flip() is copy() is // copy every reachable cell.
// copy also its //forwarding // pointer.
134
Garbage Collection Initial configuration free+1 > top_of_space
135
Garbage Collection Initial configuration NULL freelist
p // memory is also packed // and contiguous q
136
Garbage Collection Results of applying copy-collection
137
Example Steps through the following code if Tombstone nodes are used.
How many bytes are lost if we do p1=head = NULL; struct node { int key; struct node *next; struct node *prev; } head,p1; p1 = (struct node *) malloc (sizeof(struct node)); head = p1; p1->next =(struct node *) malloc (sizeof(struct node)); p1->prev = (struct node *) malloc (sizeof(struct node)); p1= p1->next; p1->next = head->prev; p1->prev = head; p1 = head->prev; p1->next = head; p1->prev = head->next; How many bytes for tombstone nodes, Lock-and-key? Trace it for RC, mark and sweep, and copy collection.
138
Example Steps through the following code if Tombstone nodes are used.
struct node { int key; struct node *next; struct node *prev; } head,p1; p1 = (struct node *) malloc (sizeof(struct node)); head = p1; p1->next =(struct node *) malloc (sizeof(struct node)); p1->prev = (struct node *) malloc (sizeof(struct node)); p1= p1->next; p1->next=head->prev; p1->prev = head; p1 = head->prev; p1->next = head; p1->prev = head->next; head p1 p1 p1
139
Example Steps through the following code if Tombstone nodes are used.
struct node { int key; struct node *next; struct node *prev; } head,p1; p1 = (struct node *) malloc (sizeof(struct node)); head = p1; p1->next =(struct node *) malloc (sizeof(struct node)); p1->prev = (struct node *) malloc (sizeof(struct node)); p1= p1->next; p1->next=head->prev; p1->prev = head; p1 = head->prev; p1->next = head; p1->prev = head->next; head p1 How many bytes are lost if we do p1=head = NULL;
140
Example Steps through the following code if Tombstone nodes are used.
struct node { int key; struct node *next; struct node *prev; } head,p1; p1 = (struct node *) malloc (sizeof(struct node)); head = p1; p1->next =(struct node *) malloc (sizeof(struct node)); p1->prev = (struct node *) malloc (sizeof(struct node)); p1= p1->next; p1->next=head->prev; p1->prev = head; p1 = head->prev; p1->next = head; p1->prev = head->next; head 3 2 3 p1 What are the RC values?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.