![]() |
VOOZH | about |
Prerequisite - Buddy Allocation | Set 1
Question: Write a program to implement the buddy system of memory allocation and deallocation in Operating Systems.
Explanation -
As we already know from Set 1, the allocation is done via the usage of free lists. Now, for deallocation, we will maintain an extra data structure-a Map (unordered_set in C++, HashMap in Java) with the starting address of segment as key and size of the segment as value and update it whenever an allocation request comes. Now, when a deallocation request comes, we will first check the map to see if it is a valid request. If so, we will then add the block to the free list tracking blocks of their sizes. Then, we will search the free list to see if its buddy is free-if so, we will merge the blocks and place them on the free list above them (which tracks blocks of double the size), else we will not coalesce and simply return after that.
How to know which block is a given block's buddy?
Let us define two terms-buddyNumber and buddyAddress. The buddyNumber of a block is calculated by the formula:
(base_address-starting_address_of_main_memory)/block_sizeWe note that this is always an integer, as both numerator and denominator are powers of 2. Now, a block will be another block's buddy if both of them were formed by the splitting of the same bigger block. For example, if 4 consecutive allocation requests of 16 bytes come, we will end up with blocks 0-15, 16-31, 32-47, 48-63 where blocks 0-15 and 16-31 are buddies (as they were formed by splitting block 0-32) but 0-15 and 32-47 aren't. The buddyAddress of a block is the starting index of its buddy block, given by the formula:
block_starting_address+block_size (if buddyNumber is even)
block_starting_address-block_size (if buddyNumber is odd)
Thus, all we have to do is find this buddyAddress in the free list (by comparing with all the starting addresses in that particular list), and if present, coalescing can be done.
Examples:
Let us see how the algorithm proceeds by tracking a memory block of size 128 KB. Initially, the free list is: {}, {}, {}, {}, {}, {}, {}, { (0, 127) }
Implementation -
Below is the complete program.
Memory from 0 to 15 allocate Memory from 16 to 31 allocated Memory from 32 to 47 allocate Memory from 48 to 63 allocated Memory block from 0 to 15 freed Sorry, invalid free request Memory block from 32 to 47 freed Memory block from 16 to 31 freed Coalescing of blocks starting at 0 and 16 was done
Time Complexity -
As already discussed in set 1, the time complexity of allocation is O(log(n)). For deallocation, in the worst case, all the allocated blocks can be of size 1 unit, which will then require O(n) time to scan the list for coalescing. However, in practice, it is highly unlikely that such an allocation will happen so it is generally much faster than linear time.