-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryPool.cpp
More file actions
86 lines (83 loc) · 2.19 KB
/
MemoryPool.cpp
File metadata and controls
86 lines (83 loc) · 2.19 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
75
76
77
78
79
80
81
82
83
84
85
86
#include "MemoryPool.h"
void* MemoryPool::memoryPool_malloc() {
if (firstBlock == NULL) {
firstBlock = (MemoryBlock*)malloc(sizeof(MemoryBlock) + objSize * initObjCount);
if (firstBlock == NULL) {
perror("malloc is failed!");
return NULL;
}
firstBlock->dataSize = objSize * initObjCount;
firstBlock->freeNum = initObjCount - 1;
firstBlock->visitedData = 1;
firstBlock->next = NULL;
return (void*)firstBlock->data;
}
else {
MemoryBlock* pmb = firstBlock;
while (pmb->freeNum <= 0 && pmb->next != NULL) {
pmb = pmb->next;
}
if (pmb->freeNum <= 0 && pmb->next == NULL) {
if (growObjCount == 0) {
return NULL;
}
MemoryBlock* newBlock = (MemoryBlock*)malloc(sizeof(MemoryBlock) + objSize * growObjCount);
if (newBlock == NULL) {
perror("malloc is failed!");
return NULL;
}
newBlock->dataSize = objSize * growObjCount;
newBlock->freeNum = growObjCount - 1;
newBlock->visitedData = 1;
newBlock->next = NULL;
pmb->next = newBlock;
return (void*)newBlock->data;
}
else {
unsigned int index = 0;
while ((1 << index) & pmb->visitedData) {
index++;
}
void* p = pmb->data + index * objSize;
pmb->freeNum--;
pmb->visitedData |= (1 << index);
return p;
}
}
}
void MemoryPool::memoryPool_free(void* p) {
MemoryBlock* pmb = firstBlock;
if (pmb && (unsigned int)p < (unsigned int)(void*)pmb->data && (unsigned int)p >= (unsigned int)(void*)pmb->data + pmb->dataSize) {
pmb = pmb->next;
}
if (pmb == NULL) {
perror("free is failed! this pointer is not at this memory pool.");
return;
}
unsigned int bytes = (unsigned int)p - (unsigned int)(void*)pmb->data;
if (bytes % objSize != 0) {
perror("free is failed! this pointer has a bad address between this memory pool.");
return;
}
unsigned int index = bytes / objSize;
if ((pmb->visitedData >> index) % 2 == 0) {
perror("free is failed! this pointer address which is in this memory pool is not used.");
return;
}
else {
pmb->visitedData ^= (1 << index);
pmb->freeNum++;
}
return;
}
void MemoryPool::clear() {
MemoryBlock* pmb = firstBlock;
if (pmb != NULL) {
while (pmb->next != NULL) {
MemoryBlock* p = pmb;
pmb = pmb->next;
free(p);
}
free(pmb);
}
}