-
Notifications
You must be signed in to change notification settings - Fork 0
/
A1DynamicMem.java
73 lines (53 loc) · 1.83 KB
/
A1DynamicMem.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Class: A1DynamicMem
// Implements DynamicMem
// Does not implement defragment (which is for A2).
public class A1DynamicMem extends DynamicMem {
public A1DynamicMem() {
super();
}
public A1DynamicMem(int size) {
super(size);
}
public A1DynamicMem(int size, int dict_type) {
super(size, dict_type);
}
public void Defragment() {
return ;
}
// In A1, you need to implement the Allocate and Free functions for the class A1DynamicMem
// Test your memory allocator thoroughly using Doubly Linked lists only (A1List.java).
public int Allocate(int blockSize) {
if (blockSize <= 0) {
return -1;
}
Dictionary memoryBlk = freeBlk.Find(blockSize, false);
if (memoryBlk != null) {
int address = memoryBlk.address, size = memoryBlk.size;
// freeBlk and allockBlk should have memory blocks with size > 0
allocBlk.Insert(address, blockSize, address);
if (size-blockSize > 0) {
freeBlk.Insert(address+blockSize, size - blockSize, size - blockSize);
}
freeBlk.Delete(memoryBlk);
return address;
}
return -1;
}
public int Free(int startAddr) {
if (startAddr < 0) {
return -1;
}
Dictionary memoryBlk;
for (memoryBlk = allocBlk.getFirst(); memoryBlk != null; memoryBlk = memoryBlk.getNext()) {
if (memoryBlk.address == startAddr) {
break;
}
}
if (memoryBlk != null) {
freeBlk.Insert(memoryBlk.address, memoryBlk.size, memoryBlk.size);
allocBlk.Delete(memoryBlk);
return 0;
}
return -1;
}
}