-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmem.c
74 lines (65 loc) · 1.65 KB
/
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
/*======================================================================
* Implementation of memory allocator
*======================================================================*/
#include "mem.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct Freer {
MemFreer freer;
void *closure;
struct Freer *next;
} Freer;
static Freer *freers;
#if DEBUG
#define TRACEF(args) (printf args, printf("\n"))
#else
#define TRACEF(args)
#endif
void *Mem_new(size_t size)
{
void *mem;
Freer *f;
TRACEF(("Mem_new(%#x)", size));
if ((mem = malloc(size)) != NULL) { /* Initial attempt */
TRACEF(("Allocated %#x..%#x", mem, (char*)mem+size));
return mem; /* Success */
}
for (f=freers; f; f=f->next) {
TRACEF(("trying freer %#x(%#x)", f->freer, f->closure));
if (f->freer(f->closure, size)) { /* Freed some memory? */
TRACEF(("freer freed some memory"));
if ((mem = malloc(size)) != NULL) { /* Yes: retry malloc */
TRACEF(("Allocated %#x..%#x", mem, (char*)mem+size));
return mem;
}
}
}
fprintf(stderr, "Out of memory\n");
exit(1);
return NULL;
}
void Mem_free(void *addr)
{
TRACEF(("Freeing %#x", addr));
free(addr);
}
void Mem_add_freer(MemFreer freer, void *closure)
{
Freer *f = NEW(Freer);
f->freer = freer;
f->closure = closure;
f->next = freers;
freers = f;
}
void Mem_remove_freer(MemFreer freer, void *closure)
{
Freer **pf, *f;
for (pf = &freers; (f=*pf) != NULL; pf=&f->next) {
if (f->freer == freer && f->closure == closure) {
*pf = f->next; /* remove from chain */
Mem_free(f);
return;
}
}
/* fprintf(stderr, "Mem_remove_freer: entry not found\n"); */
}