Archived

This topic is now archived and is closed to further replies.

OleKaiwalker

My Memory Management

Recommended Posts

Hey, I have looked a bit into memory management, since resizable array and such would create several fragmentations. My Allocater class is not finished yet, especially a realloc function is needed, but before I go on completing and optimizing it, I''d like you to say, what you think of the way, I''ve done it! My main goal is safe alloction!!!!! Remember, it''s only the beginning of the code, and the constructer and deconstructer are to be altered - cause they arn''t working perfectly #define MAX_CHUNKS 128 #define POOL_SIZE 4096 class Alloc { public: Alloc(); ~Alloc(); void GetChunkHandle(unsigned int capacity); void ResizeChunk(unsigned int newCapacity); void FreeChunkHandle(); char *RetrieveChunk(); //protected: void Rearrange(); int chunkId; unsigned int chunkIndex, chunkSize; static char *memoryPool; static unsigned int poolSize, numOfChunks, poolIndex, chunkIds; static Alloc *poolChunks[MAX_CHUNKS]; }; char *Alloc::memoryPool = NULL; unsigned int Alloc:oolSize = 0; unsigned int Alloc::numOfChunks = 0; unsigned int Alloc:oolIndex = 0; unsigned int Alloc::chunkIds = 0; Alloc *Alloc:oolChunks[MAX_CHUNKS]; Alloc::Alloc(){ chunkId = -1; chunkIndex = chunkSize = 0; if (!memoryPool) memoryPool = new char[poolSize = POOL_SIZE]; if (numOfChunks == 0) memset(poolChunks, NULL, MAX_CHUNKS); } Alloc::~Alloc(){ if (memoryPool && numOfChunks == 0){ delete[] memoryPool; memoryPool = NULL; } } void Alloc::GetChunkHandle(unsigned int capacity){ chunkId = ++chunkIds; chunkSize = capacity; chunkIndex = poolIndex; poolChunks[numOfChunks++] = this; poolIndex += capacity; } void Alloc::FreeChunkHandle(){ for (int i = 0; i < numOfChunks; i++){ if (poolChunks->chunkId == chunkId) poolChunks[i] = NULL; break; } chunkSize = 0; --numOfChunks; Rearrange(); } char *Alloc::RetrieveChunk(){ if (chunkSize > 0) return (memoryPool + chunkIndex); return NULL; } void Alloc::Rearrange(){ bool changed; unsigned int chunkIndex = 0; do { changed = false; chunkIndex = 0; while (chunkIndex < numOfChunks){ if (!poolChunks[chunkIndex]){ poolChunks[chunkIndex] = poolChunks[chunkIndex + 1]; poolChunks[chunkIndex + 1] = NULL; changed = true; break; } ++chunkIndex; } } while (changed); poolIndex = 0; Alloc *thisChunk; for (chunkIndex = 0; chunkIndex < numOfChunks; chunkIndex++){ if (poolChunks[chunkIndex]->chunkIndex != poolIndex){ thisChunk = poolChunks[chunkIndex]; memcpy(memoryPool + poolIndex, memoryPool + thisChunk->chunkIndex, thisChunk->chunkSize); thisChunk->chunkIndex = poolIndex; poolIndex += thisChunk->chunkSize; } else poolIndex += poolChunks[chunkIndex]->chunkSize; } }

Share this post


Link to post
Share on other sites