Best fit algorithm for memory management: The memory partition in which there is a minimum loss on the allocation of the process is the best-fit memory partition that is allocated to the process.
We have already discussed one best-fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list where the deletion of allocated nodes is also possible.
Examples:Â
Input : blockSize[] = {100, 500, 200} processSize[] = {95, 417, 112, 426} Output : Block with size 426 can't be allocated Tag Block ID Size 0 0 95 1 1 417 2 2 112 After deleting node with tag id 1. Tag Block ID Size 0 0 95 2 2 112 3 1 426
Â
Approach: The idea is to assign a unique tag id to each memory block. Each process of different sizes are given block id, which signifies to which memory block they belong to, and unique tag id to delete particular process to free up space. Create a free list of given memory block sizes and allocated list of processes.
Create allocated list:Â
Create an allocated list of given process sizes by finding the most appropriate or best memory block to allocate memory from. If the memory block is not found, then simply print it. Otherwise, create a node and add it to the allocated linked list.
Delete process:Â
Each process is given a unique tag id. Delete the process node from the allocated linked list to free up some space for other processes. After deleting, use the block id of the deleted node to increase the memory block size in the free list.
Below is the implementation of the approach:Â
Â
C++
// C++ implementation of program // for best fit algorithm for memory // management using linked list Â
#include <bits/stdc++.h> using namespace std; Â
// Two global counters int g = 0, k = 0; Â
// Structure for free list struct free { Â Â Â Â int tag; Â Â Â Â int size; Â Â Â Â struct free * next; }* free_head = NULL, *prev_free = NULL; Â
// Structure for allocated list struct alloc { Â Â Â Â int block_id; Â Â Â Â int tag; Â Â Â Â int size; Â Â Â Â struct alloc* next; }* alloc_head = NULL, *prev_alloc = NULL; Â
// Function to create free // list with given sizes void create_free( int c) {     struct free * p = ( struct free *)         malloc ( sizeof ( struct free ));     p->size = c;     p->tag = g;     p->next = NULL;     if (free_head == NULL)         free_head = p;     else         prev_free->next = p;     prev_free = p;     g++; } Â
// Function to print free list which // prints free blocks of given sizes void print_free() { Â Â Â Â struct free * p = free_head; Â Â Â Â cout << "Tag\tSize\n" ; Â Â Â Â while (p != NULL) { Â Â Â Â Â Â Â Â cout << p->tag << "\t" Â Â Â Â Â Â Â Â Â Â Â Â Â << p->size << "\n" ; Â Â Â Â Â Â Â Â p = p->next; Â Â Â Â } } Â
// Function to print allocated list which // prints allocated blocks and their block ids void print_alloc() {     struct alloc* p = alloc_head;     cout << "Tag\tBlock ID\tSize\n" ;     while (p != NULL) {         cout << p->tag << "\t " << p->block_id              << "\t\t" << p->size << "\n" ;         p = p->next;     } } Â
// Function to allocate memory to // blocks as per Best fit algorithm void create_alloc( int c) {     // create node for process of given size     struct alloc* q = ( struct alloc*)         malloc ( sizeof ( struct alloc));     q->size = c;     q->tag = k;     q->next = NULL;     struct free * p = free_head; Â
    // Temporary node r of free     // type to find the best and     // most suitable free node to     // allocate space     struct free * r = ( struct free *)         malloc ( sizeof ( struct free ));     r->size = 99999; Â
    // Loop to find best choice     while (p != NULL) {         if (q->size <= p->size) {             if (p->size < r->size)                 r = p;         }         p = p->next;     } Â
    // Node found to allocate     // space from     if (r->size != 99999) {         // Adding node to allocated list         q->block_id = r->tag;         r->size -= q->size;         if (alloc_head == NULL)             alloc_head = q;         else {             prev_alloc = alloc_head;             while (prev_alloc->next != NULL)                 prev_alloc = prev_alloc->next;             prev_alloc->next = q;         }         k++;     } Â
    // Node with size not found     else         cout << "Block with size "              << c << " can't be allocated\n" ; } Â
// Function to delete node from // allocated list to free some space void delete_alloc( int t) {     // Standard delete function     // of a linked list node     struct alloc *p = alloc_head, *q = NULL; Â
    // First, find the node according     while (p != NULL)     // to given tag id     {         if (p->tag == t)             break ;         q = p;         p = p->next;     }     if (p == NULL)         cout << "Tag ID doesn't exist\n" ;     else if (p == alloc_head)         alloc_head = alloc_head->next;     else         q->next = p->next;     struct free * temp = free_head;     while (temp != NULL) {         if (temp->tag == p->block_id) {             temp->size += p->size;             break ;         }         temp = temp->next;     } } Â
// Driver Code int main() { Â Â Â Â int blockSize[] = { 100, 500, 200 }; Â Â Â Â int processSize[] = { 95, 417, 112, 426 }; Â Â Â Â int m = sizeof (blockSize) Â Â Â Â Â Â Â Â Â Â Â Â / sizeof (blockSize[0]); Â Â Â Â int n = sizeof (processSize) Â Â Â Â Â Â Â Â Â Â Â Â / sizeof (processSize[0]); Â
    for ( int i = 0; i < m; i++)         create_free(blockSize[i]); Â
    for ( int i = 0; i < n; i++)         create_alloc(processSize[i]); Â
    print_alloc(); Â
    // block of tag id 1 deleted     // to free space for block of size 426     delete_alloc(1); Â
    create_alloc(426);     cout << "After deleting block"          << " with tag id 1.\n" ;     print_alloc(); } |
Python3
# Python3 implementation of the First # sit memory management algorithm # using linked list Â
# Two global counters g = 0 ; k = 0 Â
# Structure for free list class free: Â Â Â Â def __init__( self ): Â Â Â Â Â Â Â Â self .tag = - 1 Â Â Â Â Â Â Â Â self .size = 0 Â Â Â Â Â Â Â Â self . next = None free_head = None ; prev_free = None Â
# Structure for allocated list class alloc: Â Â Â Â def __init__( self ): Â Â Â Â Â Â Â Â self .block_id = - 1 Â Â Â Â Â Â Â Â self .tag = - 1 Â Â Â Â Â Â Â Â self .size = 0 Â Â Â Â Â Â Â Â self . next = None Â
alloc_head = None ;prev_alloc = None Â
# Function to create free # list with given sizes def create_free(c):     global g,prev_free,free_head     p = free()     p.size = c     p.tag = g     p. next = None     if free_head is None :         free_head = p     else :         prev_free. next = p     prev_free = p     g + = 1 Â
Â
# Function to print free list which # prints free blocks of given sizes def print_free():     p = free_head     print ( "Tag\tSize" )     while (p ! = None ) :         print ( "{}\t{}" . format (p.tag,p.size))         p = p. next      Â
Â
# Function to print allocated list which # prints allocated blocks and their block ids def print_alloc():     p = alloc_head     print ( "Tag\tBlock ID\tSize" )     while (p is not None ) :         print ( "{}\t{}\t{}\t" . format (p.tag,p.block_id,p.size))         p = p. next      Â
Â
# Function to allocate memory to # blocks as per First fit algorithm def create_alloc(c):     global k,alloc_head     # create node for process of given size     q = alloc()     q.size = c     q.tag = k     q. next = None     p = free_head Â
    # Iterate to find first memory     # block with appropriate size     while (p ! = None ) :         if (q.size < = p.size):             break         p = p. next      Â
    # Node found to allocate     if (p ! = None ) :         # Adding node to allocated list         q.block_id = p.tag         p.size - = q.size         if (alloc_head = = None ):             alloc_head = q         else :             prev_alloc = alloc_head             while (prev_alloc. next ! = None ):                 prev_alloc = prev_alloc. next             prev_alloc. next = q                  k + = 1          else : # Node found to allocate space from         print ( "Block of size {} can't be allocated" . format (c)) Â
# Function to delete node from # allocated list to free some space def delete_alloc(t):     global alloc_head     # Standard delete function     # of a linked list node     p = alloc_head; q = None Â
    # First, find the node according     # to given tag id     while (p ! = None ) :         if (p.tag = = t):             break         q = p         p = p. next          if (p = = None ):         print ( "Tag ID doesn't exist" )     elif (p = = alloc_head):         alloc_head = alloc_head. next     else :         q. next = p. next     temp = free_head     while (temp ! = None ) :         if (temp.tag = = p.block_id) :             temp.size + = p.size             break                  temp = temp. next      Â
Â
# Driver Code if __name__ = = '__main__' : Â Â Â Â blockSize = [ 100 , 500 , 200 ] Â Â Â Â processSize = [ 417 , 112 , 426 , 95 ] Â Â Â Â m = len (blockSize) Â Â Â Â n = len (processSize) Â
    for i in range (m):         create_free(blockSize[i]) Â
    for i in range (n):         create_alloc(processSize[i]) Â
    print_alloc() Â
    # Block of tag id 0 deleted     # to free space for block of size 426     delete_alloc( 0 ) Â
    create_alloc( 426 )     print ( "After deleting block with tag id 0." )     print_alloc() |
Java
// Java implementation of program // for best fit algorithm for memory // management using linked list Â
import java.util.*; Â
// Class for free list class Free { Â Â Â Â int tag; Â Â Â Â int size; Â Â Â Â Free next; Â
    public Free( int tag, int size)     {         this .tag = tag;         this .size = size;         next = null ;     } } Â
// Class for allocated list class Alloc { Â Â Â Â int block_id; Â Â Â Â int tag; Â Â Â Â int size; Â Â Â Â Alloc next; Â
    public Alloc( int tag, int size)     {         this .tag = tag;         this .size = size;         next = null ;     } } Â
public class MemoryManagement { Â
    // Two global counters     static int g = 0 , k = 0 ; Â
    // Head of free list     static Free free_head = null ;     static Free prev_free = null ; Â
    // Head of allocated list     static Alloc alloc_head = null ;     static Alloc prev_alloc = null ; Â
    // Function to create free     // list with given sizes     public static void create_free( int c)     {         Free p = new Free(g, c);         if (free_head == null )             free_head = p;         else             prev_free.next = p;         prev_free = p;         g++;     } Â
    // Function to print free list which     // prints free blocks of given sizes     public static void print_free()     {         Free p = free_head;         System.out.println( "Tag\tSize" );         while (p != null ) {             System.out.println(p.tag + "\t" + p.size);             p = p.next;         }     } Â
    // Function to print allocated list which     // prints allocated blocks and their block ids     public static void print_alloc()     {         Alloc p = alloc_head;         System.out.println( "Tag\tBlock ID\tSize" );         while (p != null ) {             System.out.println(p.tag + "\t " + p.block_id                     + "\t\t" + p.size);             p = p.next;         }     } Â
    // Function to allocate memory to     // blocks as per Best fit algorithm     public static void create_alloc( int c)     {         // create node for process of given size         Alloc q = new Alloc(k, c); Â
        Free p = free_head; Â
        // Temporary node r of free         // type to find the best and         // most suitable free node to         // allocate space         Free r = new Free( 0 , 99999 ); Â
        // Loop to find best choice         while (p != null ) {             if (q.size <= p.size) {                 if (p.size < r.size)                     r = p;             }             p = p.next;         } Â
        // Node found to allocate         // space from         if (r.size != 99999 ) {             // Adding node to allocated list             q.block_id = r.tag;             r.size -= q.size;             if (alloc_head == null )                 alloc_head = q;             else {                 prev_alloc = alloc_head;                 while (prev_alloc.next != null )                     prev_alloc = prev_alloc.next;                 prev_alloc.next = q;             }             k++;         } Â
        // Node with size not found         else             System.out.println( "Block with size "                     + c + " can't be allocated\n" );     } Â
    // Function to delete node from     // allocated list to free some space     public static void delete_alloc( int t)     {         // Standard delete function         // of a linked list node         Alloc p = alloc_head, q = null ; Â
        // First, find the node according         while (p != null )         // to given tag id         {             if (p.tag == t)                 break ;             q = p;             p = p.next;         }         if (p == null )             System.out.println( "Tag ID doesn't exist\n" );         else if (p == alloc_head)             alloc_head = alloc_head.next;         else             q.next = p.next;         Free temp = free_head;         while (temp != null ) {             if (temp.tag == p.block_id) {                 temp.size += p.size;                 break ;             }             temp = temp.next;         }     } Â
    // Driver Code     public static void main(String[] args)     {         int [] blockSize = new int [] { 100 , 500 , 200 };         int [] processSize = new int [] { 95 , 417 , 112 , 426 };         int m = blockSize.length;         int n = processSize.length; Â
        for ( int i = 0 ; i < m; i++)             create_free(blockSize[i]); Â
        for ( int i = 0 ; i < n; i++)             create_alloc(processSize[i]); Â
        print_alloc(); Â
        // block of tag id 1 deleted         // to free space for block of size 426         delete_alloc( 1 ); Â
        create_alloc( 426 );         System.out.println( "After deleting block"                 + " with tag id 1." );         print_alloc();     } } |
C#
// C# implementation of program // for best fit algorithm for memory // management using linked list Â
using System; Â
// Class for free list class Free { Â Â Â Â public int tag; Â Â Â Â public int size; Â Â Â Â public Free next; Â
    public Free( int tag, int size)     {         this .tag = tag;         this .size = size;         next = null ;     } } Â
// Class for allocated list class Alloc { Â Â Â Â public int block_id; Â Â Â Â public int tag; Â Â Â Â public int size; Â Â Â Â public Alloc next; Â
    public Alloc( int tag, int size)     {         this .tag = tag;         this .size = size;         next = null ;     } } Â
public class MemoryManagement {     // Two global counters     static int g = 0, k = 0; Â
    // Head of free list     static Free free_head = null ;     static Free prev_free = null ; Â
    // Head of allocated list     static Alloc alloc_head = null ;     static Alloc prev_alloc = null ; Â
    // Function to create free     // list with given sizes     public static void create_free( int c)     {         Free p = new Free(g, c);         if (free_head == null )             free_head = p;         else             prev_free.next = p;         prev_free = p;         g++;     } Â
    // Function to print free list which     // prints free blocks of given sizes     public static void print_free()     {         Free p = free_head;         Console.WriteLine( "Tag\tSize" );         while (p != null )         {             Console.WriteLine(p.tag + "\t" + p.size);             p = p.next;         }     } Â
    // Function to print allocated list which     // prints allocated blocks and their block ids     public static void print_alloc()     {         Alloc p = alloc_head;         Console.WriteLine( "Tag\tBlock ID\tSize" );         while (p != null )         {             Console.WriteLine(p.tag + "\t " + p.block_id                     + "\t\t" + p.size);             p = p.next;         }     } Â
    // Function to allocate memory to     // blocks as per Best fit algorithm     public static void create_alloc( int c)     {         // create node for process of given size         Alloc q = new Alloc(k, c); Â
        Free p = free_head; Â
        // Temporary node r of free         // type to find the best and         // most suitable free node to         // allocate space         Free r = new Free(0, 99999); Â
        // Loop to find best choice         while (p != null )         {             if (q.size <= p.size)             {                 if (p.size < r.size)                     r = p;             }             p = p.next;         } Â
        // Node found to allocate         // space from         if (r.size != 99999)         {             // Adding node to allocated list             q.block_id = r.tag;             r.size -= q.size;             if (alloc_head == null )                 alloc_head = q;             else             {                 prev_alloc = alloc_head;                 while (prev_alloc.next != null )                     prev_alloc = prev_alloc.next;                 prev_alloc.next = q;             }             k++;         } Â
        // Node with size not found         else             Console.WriteLine( "Block with size "                     + c + " can't be allocated\n" );     } Â
    // Function to delete node from     // allocated list to free some space     public static void delete_alloc( int t)     {         // Standard delete function         // of a linked list node         Alloc p = alloc_head, q = null ; Â
        // First, find the node according         while (p != null )         // to given tag id         {             if (p.tag == t)                 break ;             q = p;             p = p.next;         }         if (p == null )             Console.WriteLine( "Tag ID doesn't exist\n" );         else if (p == alloc_head)             alloc_head = alloc_head.next;         else             q.next = p.next;         Free temp = free_head;         while (temp != null )         {             if (temp.tag == p.block_id)             {                 temp.size += p.size;                 break ;             }             temp = temp.next;         }     } Â
    // Driver Code     public static void Main( string [] args)     {         int [] blockSize = new int [] { 100, 500, 200 };         int [] processSize = new int [] { 95, 417, 112, 426 };         int m = blockSize.Length;         int n = processSize.Length; Â
        for ( int i = 0; i < m; i++)             create_free(blockSize[i]); Â
        for ( int i = 0; i < n; i++)             create_alloc(processSize[i]); Â
        print_alloc(); Â
        // block of tag id 1 deleted         // to free space for block of size 426         delete_alloc(1); Â
        create_alloc(426);         Console.WriteLine( "After deleting block"                 + " with tag id 1." );         print_alloc();     } } |
Javascript
// Javascript implementation of program // for best fit algorithm for memory // management using linked list Â
// Two global counters let g = 0, k = 0; Â
// Structure for free list class Free { Â Â Â Â constructor(tag, size, next) { Â Â Â Â Â Â Â Â this .tag = tag; Â Â Â Â Â Â Â Â this .size = size; Â Â Â Â Â Â Â Â this .next = next; Â Â Â Â } } Â
let freeHead = null , prevFree = null ; Â
// Structure for allocated list class Alloc { Â Â Â Â constructor(blockId, tag, size, next) { Â Â Â Â Â Â Â Â this .blockId = blockId; Â Â Â Â Â Â Â Â this .tag = tag; Â Â Â Â Â Â Â Â this .size = size; Â Â Â Â Â Â Â Â this .next = next; Â Â Â Â } } Â
let allocHead = null , prevAlloc = null ; Â
// Function to create free // list with given sizes function createFree(c) { Â Â Â Â let p = new Free(g, c, null ); Â Â Â Â if (freeHead == null ) { Â Â Â Â Â Â Â Â freeHead = p; Â Â Â Â } else { Â Â Â Â Â Â Â Â prevFree.next = p; Â Â Â Â } Â Â Â Â prevFree = p; Â Â Â Â g++; } Â
// Function to print free list which // prints free blocks of given sizes function printFree() { Â Â Â Â let p = freeHead; Â Â Â Â console.log( "Tag\tSize" ); Â Â Â Â while (p != null ) { Â Â Â Â Â Â Â Â console.log(p.tag + "\t" + p.size); Â Â Â Â Â Â Â Â p = p.next; Â Â Â Â } } Â
// Function to print allocated list which // prints allocated blocks and their block ids function printAlloc() {     let p = allocHead;     console.log( "Tag\tBlock ID\tSize" );     while (p != null ) {         console.log(p.tag + "\t " + p.blockId + "\t\t" + p.size);         p = p.next;     } } Â
Â
// Function to allocate memory to // blocks as per Best fit algorithm function createAlloc(c) { Â
    // create node for process of given size     let q = new Alloc( null , k, c, null );     let p = freeHead;          // Temporary node r of free     // type to find the best and     // most suitable free node to     // allocate space     let r = new Free( null , 0, null );     r.size = 99999;          // Loop to find best choice     while (p != null ) {         if (q.size <= p.size) {             if (p.size < r.size) {                 r = p;             }         }         p = p.next;     }               // Node found to allocate     // space from     if (r.size != 99999) {         // Adding node to allocated list         q.blockId = r.tag;         r.size -= q.size;         if (allocHead == null ) {             allocHead = q;         } else {             prevAlloc = allocHead;             while (prevAlloc.next != null ) {                 prevAlloc = prevAlloc.next;             }             prevAlloc.next = q;         }         k++;     } Â
    // Node with size not found     else {         console.log( "Block with size " + c + " can't be allocated" );     } } Â
// Function to delete node from // allocated list to free some space function deleteAlloc(t) { Â
    // Standard delete function     // of a linked list node     let p = allocHead, q = null ;          // First, find the node according     while (p != null ) {         // to given tag id         if (p.tag == t) {             break ;         }         q = p;         p = p.next;     }     if (p == null ) {         console.log( "Tag ID doesn't exist" );     } else if (p == allocHead) {         allocHead = allocHead.next;     } else {         q.next = p.next;     }     let temp = freeHead;     while (temp != null ) {         if (temp.tag == p.blockId) {             temp.size += p.size;             break ;         }         temp = temp.next;     } } Â
// Driver Code function main() { Â Â const blockSize = [100, 500, 200]; Â Â const processSize = [95, 417, 112, 426]; Â Â const m = blockSize.length; Â Â const n = processSize.length; Â
  for (let i = 0; i < m; i++) {     createFree(blockSize[i]);   } Â
  for (let i = 0; i < n; i++) {     createAlloc(processSize[i]);   } Â
  printAlloc();      // block of tag id 1 deleted   // to free space for block of size 426   deleteAlloc(1); Â
  createAlloc(426);   console.log( "After deleting block with tag id 1." );   printAlloc(); } Â
// this code is contributed by bhardwajji |
Block with size 426 can't be allocated Tag Block ID Size 0 0 95 1 1 417 2 2 112 After deleting block with tag id 1. Tag Block ID Size 0 0 95 2 2 112 3 1 426
Â
The time complexity of this program is O(m+n) as we traverse the blockSize and processSize array of sizes and create both free and allocated list.Â
The space complexity is O(m+n) as we create m+n nodes for free and allocated list respectively.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!