-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hoard.cpp
91 lines (84 loc) · 1.44 KB
/
Hoard.cpp
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
81
82
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
// create a hoard to manage the memory
class Hoard
{
public:
Hoard(int size);
~Hoard();
void *allocate(int size);
void deallocate(void *p);
private:
int size;
char *memory;
int *next;
int *prev;
int first;
int last;
int free;
};
Hoard::Hoard(int size)
{
this->size = size;
memory = new char[size];
next = new int[size];
prev = new int[size];
for (int i = 0; i < size; i++)
{
next[i] = i + 1;
prev[i] = i - 1;
}
next[size - 1] = -1;
prev[0] = -1;
first = 0;
last = size - 1;
free = size;
}
Hoard::~Hoard()
{
delete[] memory;
delete[] next;
delete[] prev;
}
void *Hoard::allocate(int size)
{
if (free == 0)
{
return nullptr;
}
int index = first;
first = next[first];
if (first != -1)
{
prev[first] = -1;
}
free--;
return memory + index;
}
void Hoard::deallocate(void *p)
{
int index = (char *)p - memory;
if (last != -1)
{
next[last] = index;
prev[index] = last;
}
last = index;
if (first == -1)
{
first = index;
}
free++;
}
/* // Application
int main()
{
Hoard hoard(10);
int *p = (int *)hoard.allocate(sizeof(int));
*p = 10;
std::cout << *p << std::endl;
hoard.deallocate(p);
p = (int *)hoard.allocate(sizeof(int));
*p = 20;
std::cout << *p << std::endl;
return 0;
} */