void* MemoryBlockAllocator::AllocMemory(size_t sizeOfBytes) { if (sizeOfBytes == 0){ return nullptr; } void* pResult = nullptr; //calculate how much of blocks we need. size_t numofRequiredblocks = (size_t)ceil((float)sizeOfBytes / (float)_blockSize); //check whether there are enough blocks for us, index of the memory block size_t startBit = this->_pBitfield->CheckEnoughSpaces(numofRequiredblocks); //if have enough blocks for the memory if (startBit != UINT_MAX) { //wirte the bits in bitfield bool success = _pBitfield->WriteBits(startBit, numofRequiredblocks); if (!success) { MessagedAssert(success == true, "Memory alloc failed!"); TDEBUG_PRINT_FL("Alloc failed! %d bytes of memory is too much to alloc\n", Debugger::VerbosityDebugger::LEVEL1, sizeOfBytes); return nullptr; } //find the memory block which contains the address we want to return to user size_t offset = align_get_boundry_offset(sizeof(MemoryBlock), _alignment); MemoryBlock* pTtemp = reinterpret_cast<MemoryBlock*>(reinterpret_cast<char*>(_pBlocks)+startBit * offset); pResult = pTtemp->GetAddress(); //record how much of blocks we alloced pTtemp->AllocBlock(numofRequiredblocks); TDEBUG_PRINT_FL("%d bytes = %d blocks of memory has been alloced\n", Debugger::VerbosityDebugger::LEVEL1, numofRequiredblocks*_blockSize, numofRequiredblocks); } else { MessagedAssert(startBit != UINT_MAX, "Memory alloc failed!"); TDEBUG_PRINT_FL("Alloc failed! %d bytes of memory is too much to alloc\n", Debugger::VerbosityDebugger::LEVEL1, sizeOfBytes); } return pResult; }