-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgarbagecollector.c
56 lines (46 loc) · 1.22 KB
/
garbagecollector.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
47
48
49
50
51
52
53
54
55
56
#include "garbagecollector.h"
extern Object* heap = NULL;
extern size_t heapSize = maxHeapSize;
extern size_t usedHeap = 0;
void* allocate(size_t size){
try{
if (usedHeap + size > maxHeapSize)
throw();
Object* newObject = malloc(sizeof(Object) + size);
newObject->collect = false;
newObject->size = size;
newObject->object = heap;
heap = newObject;
usedHeap = usedHeap + (sizeof(Object) + size);
return newObject;
} catch{
error("GC", "An error resulted when allocating an object to memory by garbage collector\n");
return NULL;
}
}
void collect(Object* object){
try{
if(object == NULL || object->collect) throw();
object->collect = true;
}
}
int gc_call() {
Object* next = heap;
Object* last = NULL;
while (next != NULL) {
if (!next->collect) {
last = next;
return 0;
}
if (last == NULL)
heap = next->object;
else
last->object = next->object;
usedHeap -= sizeof(Object) + next->size;
Object* temp = next;
next = next->object;
free(temp);
}
next = next->object;
return 0;
}