#include "FauxMemory.imp.h" class BestFitMemory : public FauxMemory { public: // Constructor BestFitMemory(int size) : FauxMemory(size){strategy = "Best fit";}; // Malloc bool allocMem(ProgramBlock* new_block){ // Increment BID (block id) , sort of like a PID. // increment if next block can only be "id + 1" this->incrementBid(); // Check if the new block is indeed the next in the sequence. if((*this->getBid()) != new_block->getId()){ return false; } // First check if new block > available free space in memory. if (new_block->getSize() > (*this->getFree())){ return false; }; // Make sure new block size is not negative or zero. if (new_block->getSize() < 1){ return false; } // Look for the best block MemBlock* best_block = NULL; int best_block_index; for(int i = 0; i < (*this->getAllBlocks()).size(); i++){ MemBlock* curr_block = (*this->getAllBlocks())[i]; // Check if current block is a hole block. if(curr_block->getId() == -1){ // Check if hole block is big enough to fit the new program block if(curr_block->getSize() >= new_block->getSize()){ // Base case if no best_block had been found so far. if(best_block == NULL){ best_block = curr_block; best_block_index = i; // Compare to see if current hole block is better than best_block so far }else if(curr_block->getSize() < best_block->getSize()){ best_block = curr_block; best_block_index = i; }; }; }; }; // Confirm that a suitable block had been found if(best_block == NULL){ return false; }; // Case program and hole blocks equal if(new_block->getSize() == best_block->getSize()){ // Set addresses new_block->setStart(best_block->getStart()); new_block->setEnd(best_block->getEnd()); (*this->getAllBlocks()).insert(this->getAllBlocks()->begin() + best_block_index, new_block); (*this->getAllBlocks()->erase(this->getAllBlocks()->begin() + best_block_index + 1)); delete best_block; // Case program block smaller } else { // Set addressess. new_block->setStart(best_block->getStart()); new_block->setEnd(best_block->getStart() + new_block->getSize() - 1); (*this->getAllBlocks()).insert(this->getAllBlocks()->begin() + best_block_index, new_block); best_block->setStart(new_block->getEnd() + 1); best_block->resize(); } // Reduce free space in the faux memory. this->setFree((*this->getFree()) - new_block->getSize()); // Sucessfull allocation return true; }; };