forked from mario-nakazawa/coding.freelist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreeList.cc
80 lines (49 loc) · 1.27 KB
/
freeList.cc
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
74
75
76
77
78
79
80
#include "freeList.h"
freeList::freeList( long int*inRAM, int size ) {
head = inRAM;
head[0] = size -2;
head[1] = NULL;
}
long int*
freeList::reserve_space( int size ) {
long int* current = head;
while (current != NULL) {
if (size > current[0]) {
std::cerr << "Memory allocation failed!" << std::endl;
current = (long int * )current[1];
}
else{
head = current + size + 2;
head[1] = current[1];
head[0] = current[0] - size - 2;
current[0] = size;
return current;}
}
return nullptr;
}
void
freeList::free_space( long int* location ) {
location[1] = (long int )head;
head = location;
}
void
freeList::coalesce_forward() {
long int* current = head;
while (current) {
int size = current[0];
long int* nextChunk = (long int*)((char*)current + (size + 2) * sizeof(long int));
if (nextChunk[0] > 0) {
current[0] += nextChunk[0] + 2;
current[1] = nextChunk[1];
} else {
current = nextChunk;
}
}
}
void freeList::print() {
long int * printHead = head;
while( printHead != NULL ) {
cout << "at " << printHead << "("<< dec <<printHead[0] << " : 0x" << hex << printHead[1] << ")\n";
printHead = (long int *)printHead[1];
}
}