BudgetAllocatorInit
Description
Initialize a BudgetAllocator over a caller-owned memory region. Carves buf into floor(buf_bytes / padded_slot_size) slots and builds an intrusive free list over them. padded_slot_size is slot_size rounded up to sizeof(void *) so each free slot can hold the intrusive next pointer.
Parameters
| Name | Direction | Description |
|---|---|---|
buf |
in,out | Caller-owned memory region used as backing storage. |
buf_bytes |
in | Size of buf in bytes. |
slot_size |
in | Allocation size class served by this allocator. |
Success
Returns a fully-initialized BudgetAllocator value.
Failure
Returns a zero-initialized allocator whose __magic is 0 when buf is NULL, slot_size is 0, or the buffer is too small to hold a single padded slot. Calling AllocatorAlloc on it will abort via ValidateAllocator.
Usage example (Cross-references)
Usage examples (Cross-references)
static bool test_basic_alloc_and_free(void) {
u8 buf[1024] = {0};
BudgetAllocator bp = BudgetAllocatorInit(buf, sizeof(buf), sizeof(Node));
Allocator *alloc = ALLOCATOR_OF(&bp);
Node *a = (Node *)AllocatorAlloc(alloc, sizeof(Node), true); // 256 bytes / padded(sizeof(Node)) = a few slots, exhaust them.
u8 buf[256] = {0};
BudgetAllocator bp = BudgetAllocatorInit(buf, sizeof(buf), sizeof(Node));
Allocator *alloc = ALLOCATOR_OF(&bp); static bool test_free_then_alloc_recycles(void) {
u8 buf[1024] = {0};
BudgetAllocator bp = BudgetAllocatorInit(buf, sizeof(buf), sizeof(Node));
Allocator *alloc = ALLOCATOR_OF(&bp); static bool test_oversized_request_fails(void) {
u8 buf[256] = {0};
BudgetAllocator bp = BudgetAllocatorInit(buf, sizeof(buf), sizeof(int));
Allocator *alloc = ALLOCATOR_OF(&bp);
void *big = AllocatorAlloc(alloc, 4096, true); // alloc must therefore return NULL on the very first call.
u8 buf[4] = {0};
BudgetAllocator bp = BudgetAllocatorInit(buf, sizeof(buf), sizeof(Node));
bool ok = (bp.slot_count == 0);- In
Budget.c:135:
}
BudgetAllocator BudgetAllocatorInit(void *buf, size buf_bytes, size slot_size) {
return budget_build(buf, buf_bytes, slot_size, sizeof(void *));
}
Last updated on