-
Notifications
You must be signed in to change notification settings - Fork 0
/
alloc.c
46 lines (41 loc) · 1007 Bytes
/
alloc.c
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
#include "gc.h"
#include "alloc.h"
word allocate (word size)
{
size += OBJ_HEADER_SIZE;
word nextFree;
word p = freeStart;
word lag = null;
while ((p != null) && (DATA_OF_WORD(mem[p]) < size)){
lag = p;
p = POINTER_OF_WORD(mem[p+1]);
}
if (p == null) return null;
word unused = DATA_OF_WORD(mem[p]) - size;
if (unused > OBJ_HEADER_SIZE) {
nextFree = p+size;
mem[nextFree] = WORD_OF_DATA(unused);
mem[nextFree+1] = mem[p+1];
}
else {
size += unused;
nextFree = POINTER_OF_WORD(mem[p+1]);
}
if (lag == null)
freeStart = nextFree;
else
mem[lag+1] = WORD_OF_POINTER(nextFree);
mem[p] = WORD_OF_DATA(size);
mem[p + 1] = WORD_OF_DATA(0);
// initialize the object
word i;
for (i = OBJ_HEADER_SIZE; i < size; i++)
mem[p + i] = WORD_OF_POINTER(null);
return p + OBJ_HEADER_SIZE;
}
void deallocate (word address)
{
// this version does not fix fragmentation
mem[address+1] = WORD_OF_POINTER(freeStart);
freeStart = address;
}