Athena: Memory Management (Part 2)

Following on from my previous entry, Athena: Memory Manager (Part 1), this will show my code for allocation and freeing of memory.

//
//
void * MemoryHeap::Allocate( const unsigned int inSize )
{
	//
	//
	unsigned char * pCurrentMemory = static_cast<unsigned char *>( m_memoryPool );
 
	for( unsigned int byteIdx = 0; byteIdx < kMemoryPoolSize; )
	{
		//
		//
		BasicMemoryHeader * pCurrentHeader = reinterpret_cast<BasicMemoryHeader *>( &pCurrentMemory[byteIdx] );
 
		if( pCurrentHeader->usage == kBlockUsage_UnAllocated && pCurrentHeader->size >= inSize )
		{
			//
			//
			SplitMemoryBlock( pCurrentHeader, inSize );
 
			//
			//
			pCurrentHeader->usage = kBlockUsage_Allocated;
			return pCurrentMemory + sizeof( BasicMemoryHeader );
		}
 
		byteIdx += sizeof( BasicMemoryHeader ) + pCurrentHeader->size;
	}
 
	//
	// No adequate memory block found, must be out of memory.
	OutOfMemory();
	return 0;
}

 

Unlike the memory allocation function, the free function just takes the pointer we are passing in and subtracts the size of the header from it. Since the actual block of memory is offset by the header size from the header, by going backwards we can get instant access to the header.

//
//
void MemoryHeap::Free( void * inPointer )
{
	//
	//
	unsigned char * memoryBlockOffset = static_cast<unsigned char *>( inPointer );
 
	//
	//
	BasicMemoryHeader * pBlockHeader = reinterpret_cast<BasicMemoryHeader *>( memoryBlockOffset - sizeof( BasicMemoryHeader ) );
	pBlockHeader->usage = kBlockUsage_UnAllocated;
 
	//
	//
	MergeFreeBlocks();
}

 

Thats all for now, the next entry will finish off my basic memory heap class.