1
|
1
|
|
2 /* Copyright (c) 2000 Digital Mars */
|
|
3 /* All Rights Reserved */
|
|
4
|
|
5 #include <stdio.h>
|
|
6 #include <stdlib.h>
|
|
7 #include <string.h>
|
|
8
|
6
|
9 // I needed to perfix the dir after upgrading to gc 7.0
|
|
10 #include "gc/gc.h"
|
1
|
11
|
|
12 #include "mem.h"
|
|
13
|
|
14 /* This implementation of the storage allocator uses the standard C allocation package.
|
|
15 */
|
|
16
|
|
17 Mem mem;
|
6
|
18 static bool gc_was_init = false;
|
1
|
19
|
|
20 void Mem::init()
|
|
21 {
|
|
22 GC_init();
|
6
|
23 gc_was_init = true;
|
1
|
24 }
|
|
25
|
|
26 char *Mem::strdup(const char *s)
|
|
27 {
|
|
28 char *p;
|
|
29
|
|
30 if (s)
|
|
31 {
|
|
32 p = GC_strdup(s);
|
|
33 if (p)
|
|
34 return p;
|
|
35 error();
|
|
36 }
|
|
37 return NULL;
|
|
38 }
|
|
39
|
|
40 void *Mem::malloc(size_t size)
|
|
41 { void *p;
|
|
42
|
|
43 if (!size)
|
|
44 p = NULL;
|
|
45 else
|
|
46 {
|
|
47 p = GC_malloc(size);
|
|
48 if (!p)
|
|
49 error();
|
|
50 }
|
|
51 return p;
|
|
52 }
|
|
53
|
|
54 void *Mem::calloc(size_t size, size_t n)
|
|
55 { void *p;
|
|
56
|
|
57 if (!size || !n)
|
|
58 p = NULL;
|
|
59 else
|
|
60 {
|
|
61 p = GC_malloc(size * n);
|
|
62 if (!p)
|
|
63 error();
|
|
64 memset(p, 0, size * n);
|
|
65 }
|
|
66 return p;
|
|
67 }
|
|
68
|
|
69 void *Mem::realloc(void *p, size_t size)
|
|
70 {
|
|
71 if (!size)
|
|
72 { if (p)
|
|
73 { GC_free(p);
|
|
74 p = NULL;
|
|
75 }
|
|
76 }
|
|
77 else if (!p)
|
|
78 {
|
|
79 p = GC_malloc(size);
|
|
80 if (!p)
|
|
81 error();
|
|
82 }
|
|
83 else
|
|
84 {
|
|
85 p = GC_realloc(p, size);
|
|
86 if (!p)
|
|
87 error();
|
|
88 }
|
|
89 return p;
|
|
90 }
|
|
91
|
|
92 void Mem::free(void *p)
|
|
93 {
|
|
94 if (p)
|
|
95 GC_free(p);
|
|
96 }
|
|
97
|
|
98 void *Mem::mallocdup(void *o, size_t size)
|
|
99 { void *p;
|
|
100
|
|
101 if (!size)
|
|
102 p = NULL;
|
|
103 else
|
|
104 {
|
|
105 p = GC_malloc(size);
|
|
106 if (!p)
|
|
107 error();
|
|
108 else
|
|
109 memcpy(p,o,size);
|
|
110 }
|
|
111 return p;
|
|
112 }
|
|
113
|
|
114 void Mem::error()
|
|
115 {
|
|
116 printf("Error: out of memory\n");
|
|
117 exit(EXIT_FAILURE);
|
|
118 }
|
|
119
|
|
120 void Mem::fullcollect()
|
|
121 {
|
|
122 GC_gcollect();
|
|
123 }
|
|
124
|
|
125 void Mem::mark(void *pointer)
|
|
126 {
|
|
127 (void) pointer; // necessary for VC /W4
|
|
128 }
|
|
129
|
|
130 /* =================================================== */
|
|
131
|
|
132 void * operator new(size_t m_size)
|
6
|
133 {
|
|
134 // without this we segfault with gc 7.0
|
|
135 if (!gc_was_init) {
|
|
136 mem.init();
|
|
137 }
|
1
|
138 void *p = GC_malloc(m_size);
|
|
139 if (p)
|
|
140 return p;
|
|
141 printf("Error: out of memory\n");
|
|
142 exit(EXIT_FAILURE);
|
|
143 return p;
|
|
144 }
|
|
145
|
|
146 void operator delete(void *p)
|
|
147 {
|
|
148 GC_free(p);
|
|
149 }
|
|
150
|
|
151
|