|
ADS
Algorithms and Data Structures
|
the buddy system on \( 2^m \) words More...
#include <ADS/memory/Allocators.h>
Public member functions | |
| BuddyAllocator (int m) | |
| the memory of \( 2^m \) words, one free block | |
| long | allocate (long n) |
| a block of at least \( n \) words, a power of 2, its address, or \( -1 \) | |
| void | free (long a) |
| frees the block at \( a \) | |
| long | freeWords (void) const |
| the number of the words in free blocks | |
| long | blockSize (long a) const |
| the size of the block in use at \( a \) | |
the buddy system on \( 2^m \) words
|
explicit |
the memory of \( 2^m \) words, one free block
| long ADS::BuddyAllocator::allocate | ( | long | n | ) |
a block of at least \( n \) words, a power of 2, its address, or \( -1 \)
In pseudocode (Algorithm 2.5R of TAOCP, the buddy system of Knowlton, beyond the book), \( F_k \) the free blocks of \( 2^k \) words:
\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{function}\ \mathrm{allocate}( n ) \cr 2 & \quad k \gets \lceil \log_2 n \rceil \cr 3 & \quad j \gets \text{the least } j \ge k \text{ with } F_j \ne \emptyset \cr 4 & \quad \textbf{if}\ \text{there is none}\ \textbf{then return}\ -1 \cr 5 & \quad a \gets \text{the least block of } F_j;\ F_j \gets F_j \setminus \{ a \} \cr 6 & \quad \textbf{while}\ j > k\ \textbf{do}\quad \triangleright \ \text{split, the upper halves free} \cr 7 & \qquad j \gets j - 1;\ F_j \gets F_j \cup \{ a + 2^j \} \cr 8 & \quad \textbf{return}\ a \end{array}} \]
|
nodiscard |
the size of the block in use at \( a \)
| void ADS::BuddyAllocator::free | ( | long | a | ) |
frees the block at \( a \)
In pseudocode (Algorithm 2.5S of TAOCP, beyond the book), \( 2^k \) the words of the block:
\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{procedure}\ \mathrm{free}( a ) \cr 2 & \quad \textbf{while}\ k < m\ \textbf{and}\ a \oplus 2^k \in F_k \ \textbf{do}\quad \triangleright\ \text{the buddy is free} \cr 3 & \qquad F_k \gets F_k \setminus \{ a \oplus 2^k \};\ a \gets \min( a , a \oplus 2^k );\ k \gets k + 1 \cr 4 & \quad F_k \gets F_k \cup \{ a \} \end{array}} \]
|
nodiscard |
the number of the words in free blocks