-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc_mem.c
133 lines (115 loc) · 2.53 KB
/
c_mem.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "c_mem.h"
#include "log.h"
typedef struct memblock_s
{
uint32_t lifetime;
void* ptr;
struct memblock_s* next;
} memblock_t;
memblock_t* startblock;
memblock_t* endblock;
void append_block(memblock_t* blk)
{
if (!startblock) {
startblock = blk;
endblock = blk;
return;
}
endblock->next = blk;
endblock = blk;
}
void* c_malloc(size_t size, uint32_t lifetime)
{
memblock_t* blk = malloc(sizeof(memblock_t));
blk->lifetime = lifetime;
blk->ptr = malloc(size);
blk->next = NULL;
append_block(blk);
return blk->ptr;
}
void* c_realloc(void* ptr, size_t size, uint32_t lifetime)
{
if (ptr == NULL)
return c_malloc(size, lifetime);
if (size == 0) {
free(ptr);
return NULL;
}
memblock_t* cur = startblock;
while (cur) {
if (cur->ptr == ptr)
break;
cur = cur->next;
}
cur->lifetime = lifetime;
cur->ptr = realloc(ptr, size);
return cur->ptr;
}
void remove_block(memblock_t* blk, memblock_t* prev)
{
if (startblock == endblock) { // current block is start and end
startblock = endblock = NULL;
}
else if (startblock == blk) { // current block is start
startblock = blk->next;
}
else if (endblock == blk) { // current block is end
endblock = prev;
prev->next = NULL;
}
else { // current block is somewhere in between
prev->next = blk->next;
}
free(blk->ptr);
free(blk);
}
void c_free(void* ptr)
{
if (!startblock) {
LOG_WARN("c_free: Pointer not found, possible double free");
return;
}
memblock_t* cur = startblock;
memblock_t* prev = NULL;
while (cur) {
if (cur->ptr == ptr)
break;
prev = cur;
cur = cur->next;
}
if (cur)
remove_block(cur, prev);
else
LOG_WARN("c_free: Pointer not found, possible double free");
}
void c_free_lifetime(uint32_t lifetime)
{
if (!startblock)
return;
memblock_t* cur = startblock;
memblock_t* next;
memblock_t* prev = NULL;
while (cur) {
next = cur->next;
if (cur->lifetime >= lifetime) {
remove_block(cur, prev);
}
else
prev = cur;
cur = next;
}
}
void c_free_all()
{
if (!startblock)
return;
memblock_t* cur = startblock;
memblock_t* next;
while (cur) {
next = cur->next;
free(cur->ptr);
free(cur);
cur = next;
}
startblock = NULL;
}