ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
ADS::BuddyAllocator Class Reference

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 \)

Detailed description

the buddy system on \( 2^m \) words

Constructor and destructor documentation

◆ BuddyAllocator()

ADS::BuddyAllocator::BuddyAllocator ( int m)
explicit

the memory of \( 2^m \) words, one free block

Precondition
\( 0 \le m \le 40 \), and \( 2^m \) fits in a long (\( m \le 30 \) where long has 32 bits)

Member function documentation

◆ allocate()

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}} \]

Precondition
\( n \ge 1 \)

◆ blockSize()

long ADS::BuddyAllocator::blockSize ( long a) const
nodiscard

the size of the block in use at \( a \)

Precondition
\( a \) is in use

◆ free()

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}} \]

Precondition
\( a \) was given by allocate() and is in use

◆ freeWords()

long ADS::BuddyAllocator::freeWords ( void ) const
nodiscard

the number of the words in free blocks


The documentation for this class was generated from the following file: