Program for buddy memory allocation scheme in Operating Systems | Set 1 (Allocation)

Prerequisite – Buddy System
Question: Write a program to implement the buddy system of memory allocation in Operating Systems.

Explanation –
The buddy system is implemented as follows- A list of free nodes, of all the different possible powers of 2, is maintained at all times (So if total memory size is 1 MB, we’d have 20 free lists to track-one for blocks of size 1 byte, 1 for 2 bytes, next for 4 bytes and so on).

When a request for allocation comes, we look for the smallest block bigger than it. If such a block is found on the free list, the allocation is done (say, the request is of 27 KB and the free list tracking 32 KB blocks has at least one element in it), else we traverse the free list upwards till we find a big enough block. Then we keep splitting it in two blocks-one for adding to the next free list (of smaller size), one to traverse down the tree till we reach the target and return the requested memory block to the user. If no such allocation is possible, we simply return null.

Example:
Let us see how the algorithm proceeds by tracking a memory block of size 128 KB. Initially, the free list is: {}, {}, {}, {}, {}, {}, {}, { (0, 127) }

  • Request: 32 bytes
    No such block found, so we traverse up and split the 0-127 block into 0-63, 634-127; we add 64-127 to list tracking 64 byte blocks and pass 0-63 downwards; again it is split into 0-31 and 32-63; since we have found the required block size, we add 32-63 to list tracking 32 byte blocks and return 0-31 to user.
    List is: {}, {}, {}, {}, {}, { (32, 63) }, { (64, 127) }, {}
  • Request: 7 bytes
    No such block found-split block 32-63 into two blocks, namely 32-47 and 48-63; then split 32-47 into 32-39 and 40-47; finally, return 32-39 to user (internal fragmentation of 1 byte occurs)
    List is: {}, {}, {}, { (40, 47) }, { (48, 63) }, {}, { (64, 127) }, {}
  • Request: 64 bytes
    Straight up memory segment 64-127 will be allocated as it already exists.
    List is: {}, {}, {}, { (40, 47) }, { (48, 63) }, {}, {}, {}
  • Request: 56 bytes
    Result: Not allocated

The result will be as follows:




Figure – Buddy Allocation-128 shows the starting address of next possible block (if main memory size ever increases)

Implementation –

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.io.*;
import java.util.*;
  
class Buddy {
      
    // Inner class to store lower 
    // and upper bounds of the allocated memory
    class Pair 
    {
        int lb, ub;
        Pair(int a, int b)
        {
            lb = a;
            ub = b;
        }
    }
      
    // Size of main memory
    int size; 
      
    // Array to track all 
    // the free nodes of various sizes
    ArrayList<Pair> arr[]; 
      
    // Else compiler will give warning 
    // about generic array creation
    @SuppressWarnings("unchecked"
      
    Buddy(int s)
    {
        size = s;
          
        // Gives us all possible powers of 2
        int x = (int)Math.ceil(Math.log(s) / Math.log(2)); 
          
        // One extra element is added 
        // to simplify arithmetic calculations
        arr = new ArrayList[x + 1]; 
          
        for (int i = 0; i <= x; i++)
            arr[i] = new ArrayList<>();
              
        // Initially, only the largest block is free 
        // and hence is on the free list    
        arr[x].add(new Pair(0, size - 1)); 
    }
      
    void allocate(int s)
    {
          
        // Calculate which free list to search to get the
        // smallest block large enough to fit the request
        int x = (int)Math.ceil(Math.log(s) / Math.log(2)); 
          
        int i;
        Pair temp = null;
          
        // We already have such a block
        if (arr[x].size() > 0
        {
              
            // Remove from free list 
            // as it will be allocated now
            temp = (Pair)arr[x].remove(0); 
            System.out.println("Memory from " + temp.lb 
                               + " to " + temp.ub + " allocated");
            return;
        }
          
        // If not, search for a larger block
        for (i = x + 1; i < arr.length; i++) {
              
            if (arr[i].size() == 0)
                continue;
                  
            // Found a larger block, so break    
            break
        }
          
        // This would be true if no such block was found 
        // and array was exhausted
        if (i == arr.length) 
        {
            System.out.println("Sorry, failed to allocate memory");
            return;
        }
          
        // Remove the first block
        temp = (Pair)arr[i].remove(0); 
          
        i--; 
          
        // Traverse down the list
        for (; i >= x; i--) {
              
            // Divide the block in two halves
            // lower index to half-1
            Pair newPair = new Pair(temp.lb, temp.lb 
                                     + (temp.ub - temp.lb) / 2); 
              
            // half to upper index
            Pair newPair2 = new Pair(temp.lb 
                                  + (temp.ub - temp.lb + 1) / 2, temp.ub); 
              
            // Add them to next list 
            // which is tracking blocks of smaller size
            arr[i].add(newPair);
            arr[i].add(newPair2);
              
            // Remove a block to continue the downward pass
            temp = (Pair)arr[i].remove(0); 
        }
          
        // Finally inform the user 
        // of the allocated location in memory
        System.out.println("Memory from " + temp.lb 
                            + " to " + temp.ub + " allocated");
    }
      
    public static void main(String args[]) throws IOException
    {
        int initialMemory = 0, val = 0;
          
          
        // Uncomment the below section for interactive I/O
        /*Scanner sc=new Scanner(System.in);
        initialMemory = sc.nextInt();
        Buddy obj = new Buddy(initialMemory); 
        while(true)
        {
            val = sc.nextInt();// Accept the request
            if(val <= 0)
                break;
            obj.allocate(val);// Proceed to allocate
        }*/
          
          
        initialMemory = 128;
          
        // Initialize the object with main memory size
        Buddy obj = new Buddy(initialMemory); 
        obj.allocate(32);
        obj.allocate(7);
        obj.allocate(64);
        obj.allocate(56);
    }
}

chevron_right


Output:

Memory from 0 to 31 allocated
Memory from 32 to 39 allocated
Memory from 64 to 127 allocated
Sorry, failed to allocate memory 

Time Complexity –
If the main memory size is n, we have log(n) number of different powers of 2 and hence log(n) elements in the array (named arr in the code) tracking free lists. To allocate a block, we only need to traverse the array once upwards and once downwards, hence time complexity is O(2log(n)) or simply O(logn)



My Personal Notes arrow_drop_up

CSE B Tech 3rd Year at IIT Bhubaneswar||Summer Intern 2018 IIT Roorkee

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.