//No. 2 Best fit algorithm void * bf_malloc(size_t size){ t_block b,last;//,size_of_whole_block; size_t s; s = ALIGN_SIZE(size, sizeof(char*)); //size_of_used_block += size; if (base){ //find the best block last = base; b = find_best_block (&last, s); //size_of_whole_block=last; if (b){ // size_of_whole_block->size += b->size; //is it big enough to be split if ((b->size - s)>= (BLOCK_SIZE + 4 )) split_block (b,s); b->free = 0;//mark the chunk as used } else {//otherwise we extend the heap(NO FITTING BLOCK ) b = extend_heap(last,s); if (!b) return NULL; } } else {//Heap is empty (first time allocation) b = extend_heap(NULL,s); if(!b) return(NULL); base = b; } //size_of_whole_block->size += b->size; head = b; return (b-> data); }
// public private interface unsigned char *allocate( std::size_t& size) { RAMEN_ASSERT( dev_mem_); iterator it( find_best_block( size)); if( it == end()) return 0; RAMEN_ASSERT( it->size >= size && "find best block: block smaller than size requested\n"); if( it->size - size > size_tolerance) { // we need to split the block unsigned char *ptr = it->ptr; it->split( size); return ptr; } else { unsigned char *ptr = it->ptr; size = it->size; free_list_.erase( it); return ptr; } }