MemoryPool.h
#ifndef __MEMPOOL__
#define __MEMPOOL__
#include <iostream>
struct MemoryBlock {
int address;
size_t size;
bool isFree;
MemoryBlock* next;
MemoryBlock* prev;
};
class MemoryManager {
private:
MemoryBlock* start;
char* memoryPool;
public:
MemoryManager(size_t size) {
memoryPool = new char[size];
start = new MemoryBlock;
start->address = (int)memoryPool;
start->size = size;
start->isFree = true;
start->next = nullptr;
start->prev = nullptr;
}
~MemoryManager() {
delete[] memoryPool;
MemoryBlock* current = start;
while (current != nullptr) {
MemoryBlock* nextBlock = current->next;
delete current;
current = nextBlock;
}
}
int allocate(size_t size) {
MemoryBlock* current = start;
while (current != nullptr) {
if (current->isFree && current->size >= size) {
MemoryBlock* newBlock = new MemoryBlock;
newBlock->address = current->address + size;
newBlock->size = current->size - size;
newBlock->isFree = true;
newBlock->next = current->next;
newBlock->prev = current;
current->next = newBlock;
current->size = size;
current->isFree = false;
return current->address;
}
current = current->next;
}
return nullptr; // Not enough memory
}
void deallocate(int address) {
MemoryBlock* current = start;
while (current != nullptr) {
if (current->address == address) {
// Mark the block as free
current->isFree = true;
// Merge with the next block if it's free
if (current->next != nullptr && current->next->isFree) {
MemoryBlock* nextBlock = current->next;
current->size += nextBlock->size;
current->next = nextBlock->next;
if (nextBlock->next != nullptr) {
nextBlock->next->prev = current;
}
delete nextBlock;
}
// Merge with the previous block if it's free
if (current->prev != nullptr && current->prev->isFree) {
MemoryBlock* prevBlock = current->prev;
prevBlock->size += current->size;
prevBlock->next = current->next;
if (current->next != nullptr) {
current->next->prev = prevBlock;
}
delete current;
}
return;
}
current = current->next;
}
}
};
#endif
这个内存池的设计思想是使用链表(link list)来管理用户从内存池里开辟出的memory block,allocate操作从内存池中取出所需size的memory block,它不断从未使用的空间中通过指针偏移从已经分配的内存池中取内存,而无需直接使用malloc或者new。
deallocate操作会free用户指定的memory block,并且检查前向和后向的memory block是否空闲,如果空闲则合并。
这个内存池的缺陷是无法整理不相邻的内存库,最后内存可能碎片化,这需要复杂的内存分配策略,例如最佳适配(best fit)、最差适配(worst fit)或伙伴系统(buddy system)。