This repository has been archived by the owner on Mar 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmemory_mgmt.c
113 lines (90 loc) · 2.08 KB
/
memory_mgmt.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
/*
* Project name:
* Implementace interpretu imperativního jazyka IFJ14
*
* Repository:
* https://github.com/Dasio/IFJ
*
* Team:
* Dávid Mikuš (xmikus15)
* Peter Hostačný (xhosta03)
* Tomáš Kello (xkello00)
* Adam Lučanský (xlucan01)
* Michaela Lukášová (xlukas09)
*/
#include "memory_mgmt.h"
extern InstructionVector *tape;
extern Stack stack;
GenVectorFunctions(MemItem)
static MemItemVector *memory_layout = NULL;
/**
* ALLOCATION
*/
static inline void initMemItemAndAppend(void* mem_ptr, size_t len) {
if(memory_layout == NULL) {
memory_layout = MemItemVectorInit(512);
}
MemItem item = { .mem_ptr = mem_ptr, .length = len };
MemItemVectorAppend(memory_layout, item);
}
void *mem_alloc(size_t len) {
void *mem_ptr = (void *) malloc(len);
MALLOC_TEST(mem_ptr);
initMemItemAndAppend(mem_ptr, len);
return mem_ptr;
}
void mem_ptradd(void *ptr) {
initMemItemAndAppend(ptr, 1);
}
/**
* DEALLOCATION
*/
/**
* Use only after cleaning memory. Use implodeMemory().
*/
static inline void destroyMemoryManagement() {
if(memory_layout != NULL) {
// Memory must be already cleaned
MemItemVectorFree(memory_layout);
memory_layout = NULL;
}
}
void cleanAllMemory() {
if(memory_layout == NULL)
return;
MemItem *current;
while((current = MemItemVectorLast(memory_layout)) != NULL) {
free(current->mem_ptr);
MemItemVectorPop(memory_layout);
}
}
void implodeMemory() {
cleanAllMemory();
destroyMemoryManagement();
}
void die() {
int exit_code = 0;
if(getError()) {
printError();
exit_code = getReturnError();
}
// Implosion must be after printing error, printError() may call
// stringifyToken() which reads token's string, causing invalid read.
deinitRegisteredStructures();
implodeMemory();
exit(exit_code);
}
/**
* OTHER
*/
void printAllMemoryItems() {
if(memory_layout == NULL)
return;
MemItem *current = MemItemVectorFirst(memory_layout);
if(current == NULL)
return;
MemItem *last = MemItemVectorLast(memory_layout);
for(; current <= last; current++) {
printf("Pointer %p, len: %d\n", current->mem_ptr, current->length);
}
}