mem.h
1.82 KB
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
/*******************************************************************/
/* */
/* FILE mem.h */
/* MODULE mem */
/* PROGRAM SFST */
/* AUTHOR Helmut Schmid, IMS, University of Stuttgart */
/* */
/* PURPOSE memory management functions */
/* */
/*******************************************************************/
#ifndef _MEM_H_
#define _MEM_H_
#include <stdlib.h>
#define MEMBUFFER_SIZE 100000
/***************** class Mem *************************************/
class Mem {
private:
struct MemBuffer {
char buffer[MEMBUFFER_SIZE];
struct MemBuffer *next;
};
MemBuffer *first_buffer;
long pos;
void add_buffer() {
MemBuffer *mb=(MemBuffer*)malloc(sizeof(MemBuffer));
mb->next = first_buffer;
first_buffer = mb;
pos = 0;
}
public:
Mem() { first_buffer = NULL; add_buffer(); }
~Mem() { clear(); }
void clear() {
while (first_buffer) {
MemBuffer *next = first_buffer->next;
free(first_buffer);
first_buffer = next;
}
pos = 0;
}
void *alloc( size_t n ) {
void *result;
/* do memory alignment to multiples of 4 */
if (n % 4)
n += 4 - (n % 4);
if (first_buffer == NULL || pos+n > MEMBUFFER_SIZE)
add_buffer();
if (pos+n > MEMBUFFER_SIZE)
throw "Allocation of memory block larger than MEMBUFFER_SIZE attempted!";
result = (void*)(first_buffer->buffer + pos);
pos += n;
return result;
}
//class MemError {};
};
#endif