-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemorypool.cpp
107 lines (96 loc) · 3.14 KB
/
memorypool.cpp
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
#include "memorypool.h"
#include <assert.h>
#include <iostream>
void MemoryPool::init(size_t size, int blocks) {
// init "blocks" of "size" memory
pool_ = new char[size * blocks]();
// point to top of the pool
next_ = pool_;
// in each block, create a pointer point into next block
// pool_
// \ _______ _______ _______
// \ | | | |
// --+--> ---+--> ---+--> ---+--> ...
// / |_______|_______|_______|
// /
// next_
for (int i = 0; i < blocks - 1; ++i) {
char** ptr = reinterpret_cast<char**>(&(pool_[size * i]));
*ptr = &pool_[size * (i + 1)];
}
char** ptr = reinterpret_cast<char**>(&(pool_[size * (blocks - 1)]));
*ptr = NULL;
}
void *MemoryPool::allocate() {
// "ptr" point to "next_"
// pool_
// \ _______ _______ _______ _______
// \ |///////|///////| | |
// --+-->////|///////| -> ---+--> ---+--> ...
// |///////|///////|/______|_______|
// /
// ptr ----------------/
// next_---------------/
void *ptr = next_;
assert(ptr != NULL); // Memory pool is full.
// "next_" point to next of the "next_"
// pool_
// \ _______ _______ _______ _______
// \ |///////|///////| | |
// --+-->////|///////| -> | -> ---+--> ...
// |///////|///////|/______|/______|
// / /
// ptr ----------------/ /
// next_-----------------------/
next_ = *(reinterpret_cast<char**>(&(next_[0])));
// return the block that "ptr" point into
return ptr;
}
void MemoryPool::deallocate(void *ptr) {
// pool_
// \ _______ _______ _______ _______
// \ |///////|///////|///////| |
// --+-->////| ->////|///////| -> ---+--> ...
// |///////|/_/////|///////|/______|
// / /
// ptr ----/ /
// returnPtr---/ /
// next_----------------------/
char** returnPtr = static_cast<char**>(ptr);
// (*returnPtr) point to "next_"
// pool_
// \ _______ _______ _______ _______
// \ |///////|///////|///////| |
// --+-->////| ->/-- |///////| -> ---+--> ...
// |///////|/_////\|///////|/______|
// / \ /
// ptr ----/ \_____/
// returnPtr---/ /
// next_----------------------/
*returnPtr = next_;
// "next_" point to "ptr"
// pool_
// \ _______ _______ _______ _______
// \ |///////|///////|///////| |
// --+-->////| ->/-- |///////| -> ---+--> ...
// |///////|/_////\|///////|/______|
// / \ /
// ptr ----/ \_____/
// returnPtr---/
// next_------/
next_ = static_cast<char*>(ptr);
// final
// pool_
// \ _______ _______ _______ _______
// \ |///////| |///////| |
// --+-->////| -> -- |///////| -> ---+--> ...
// |///////|/_____\|///////|/______|
// / \ /
// next_--------/ \_____/
}
void MemoryPool::free() {
if (pool_ != NULL) {
delete [] pool_;
pool_ = NULL;
}
}