-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtalloc.c
120 lines (114 loc) · 3.13 KB
/
talloc.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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <stdlib.h>
#include <stdio.h>
#include "value.h"
#include "linkedlist.h"
Value *tTree;
int started = 0;
void start(){
if (!started){
tTree= calloc(sizeof(Value),1);
tTree->type = NULL_TYPE;
started = 1;
}
}
Value *tCons(Value *car, Value *cdr){
Value *v;
v = calloc(sizeof(Value),1);
v->type = CONS_TYPE;
v->c.car = car;
v->c.cdr = cdr;
return v;
}
// Replacement for malloc that stores the pointers allocated. It should store
// the pointers in some kind of list; a linked list would do fine, but insert
// here whatever code you'll need to do so; don't call functions in the
// pre-existing linkedlist.h. Otherwise you'll end up with circular
// dependencies, since you're going to modify the linked list to use talloc.
void *talloc(size_t size){
start();
Value *new = malloc(size);
Value *pointer = malloc(sizeof(Value));
pointer->type = PTR_TYPE;
pointer->p = new;
tTree = tCons(pointer,tTree);
return new;
}
// Free all pointers allocated by talloc, as well as whatever memory you
// allocated in lists to hold those pointers.
void tfree(){
int done = 0;
Value *carV;
Value *cdrV;
while(!done){
switch (tTree->type) {
case INT_TYPE:
free(tTree);
done = 1;
break;
case DOUBLE_TYPE:
free(tTree);
done = 1;
break;
case NULL_TYPE:
free(tTree);
done = 1;
break;
case STR_TYPE:
free(tTree);
free(tTree->s);
done = 1;
break;
case PTR_TYPE:
free(tTree);
free(tTree->p);
done = 1;
break;
case CONS_TYPE:
carV = car(tTree);
cdrV = cdr(tTree);
if (carV-> type == PTR_TYPE){
free(carV->p);
}
free(carV);
free(tTree);
tTree = cdrV;
break;
case OPEN_TYPE:
free(tTree);
done = 1;
break;
case CLOSE_TYPE:
free(tTree);
done = 1;
break;
case BOOL_TYPE:
free(tTree);
done = 1;
break;
case SYMBOL_TYPE:
free(tTree);
done = 1;
break;
case PRIMITIVE_TYPE:
free(tTree);
done = 1;
break;
case VOID_TYPE:
free(tTree);
done = 1;
break;
default:
free(tTree);
done = 1;
break;
}
}
started = 0;
}
// Replacement for the C function "exit", that consists of two lines: it calls
// tfree before calling exit. It's useful to have later on; if an error happens,
// you can exit your program, and all memory is automatically cleaned up.
void texit(int status){
tfree();
exit(status);
}