Module 10 · Lesson 36 of 112

The allocator contract and a bump heap

Explain Rust’s allocation contract and trace a fixed-size bump heap through alignment, allocation failure, and deallocation.

  • Beginner to advanced
  • 8 min read
  • 11 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, a text editor, and the preceding lesson on GlobalAlloc

Your place in the module
By the end you can 4 objectives
  • Identify the caller and allocator obligations for a nonzero GlobalAlloc request
  • Distinguish an aligned zero-size sentinel from a writable allocation
  • Calculate aligned allocation ranges and cursor updates in a fixed heap
  • Explain why dropping a Box or growing a Vec does not recover bump heap capacity
Video coming soonThe allocator contract and a bump heap
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The global allocator trait
  • The frame allocator supplies physical backing for heap pages, and the heap allocator supplies variable-size blocks.
  • The alloc crate provides Box, Vec, and String in no_std, and their default heap allocations use the registered global allocator.
  • Layout specifies both the byte count and the required starting alignment.
01

What an allocation promises

4 min read

The last lesson introduced GlobalAlloc. Now you honor its contract, and start with a bump heap whose dealloc is a no-op, the simplest thing that makes Box and Vec work.

A Rust type can require stricter alignment than the byte immediately available in the heap. If a caller requests an eight-byte value with eight-byte alignment, an allocator that returns the next available byte without checking its address can invalidate the caller’s typed access. The same alignment problem exists in Linux user space. The posix_memalign(3) manual describes an interface for requesting a particular address alignment. Its own calling rules apply to that C interface. The rules below are those of Rust’s GlobalAlloc and Layout.

A describes the requested storage. Alignment is a nonzero power of two. An alignment of eight means that the returned address must be a multiple of eight. Size tells the allocator how many consecutive bytes the caller can use starting at that address. The allocator may have to skip some bytes before the start, and those skipped bytes do not count toward the requested size.

For a valid nonzero request, alloc can return a null pointer to report failure. On success, the returned pointer must be non-null and aligned, and the entire requested range must be available for the caller’s use. That range must be disjoint from every other live allocation. Ordinary alloc makes no promise that the bytes are initialized. For example, Box::new for a nonzero-sized value needs storage in which to write the value before it can expose the value through the box.

The returned address remains valid for the lifetime of that allocation. The allocator must never silently move a live block when it handles a later request. A caller may already hold pointers into the block, and updating the allocator’s own records would leave those pointers referring to the old address. An explicit realloc operation has a different contract. It may return a replacement address on success, at which point the caller uses the returned pointer and the old allocation is no longer live.

When the caller invokes dealloc, it must pass the pointer returned for the still-live allocation and the original layout for that allocation. An interior pointer, a second call after release, or a layout with the same size but a different alignment violates the contract. A raw caller that requests ten bytes at alignment eight must pass back that layout even if the allocator internally rounds its own bookkeeping to a larger size. A no-op implementation still receives calls under the same rules. The obligation belongs to the caller, even if this implementation would ignore the mismatch.

{{< callout type="note" >}}A successful zero-size request in an interface that supports one can return a non-null, correctly aligned sentinel. It supplies zero writable bytes. GlobalAlloc::alloc itself requires a nonzero size, even though Layout can describe size zero. Never call it directly with a zero-size layout.{{< /callout >}}

For a typed zero-size case, NonNull::<T>::dangling() provides a non-null pointer aligned for T. This is the kind of pointer representation a Box<()> can use without requesting storage from the global allocator. A raw caller must never use such a pointer to read or write backing bytes or pass it to GlobalAlloc::dealloc as though it came from alloc. The C malloc(3) manual describes separate zero-size behavior for glibc, so copying that behavior into a Rust trait implementation would give the wrong calling rule.

One successful nonzero allocationCallerAllocatorRequest layoutReturn aligned pointerRelease original allocation1. Caller → AllocatorRequest layout2. Allocator → CallerReturn aligned pointer3. Caller → AllocatorRelease original allocation
The caller supplies a layout, uses the returned storage on success, and releases it with the same layout
02

Allocate from a fixed region

3 min read

A bump heap starts with one reserved, contiguous region of writable memory. The region must be available before the first collection requests heap storage, and it must remain available for as long as any allocation in it is live. In the kernel, other code must leave that region exclusively available to the heap. The allocator keeps a . Initially the cursor equals the base address. The limit is the exclusive end, the address immediately after the final byte.

For each nonzero request, round the cursor address up to the next multiple of the requested alignment, including the cursor itself if it already qualifies. Call that address start. Then compute end = start + size. When the arithmetic succeeds and end is at most the limit, return the pointer at start and set the cursor to end. The range from start up to but excluding end belongs to the caller. Only the allocator’s cursor changes. All previously returned blocks stay in place.

If end equals the limit, the request fits exactly. The last byte it can use is at end - 1. If end exceeds the limit or either calculation overflows, return null and leave the cursor unchanged. A failed large request should leave whatever space was available for a later, smaller request. Rust’s valid Layout guarantees constrain the layout’s size and alignment. They do not guarantee that arithmetic on an arbitrary heap address will fit in a usize.

For a power-of-two alignment a, adding a - 1 to the cursor and clearing the low bits selected by a - 1 gives the rounded address. Use checked addition both for that rounding step and for adding the size. Align the actual address. With an unaligned base, rounding a cursor offset alone can produce an offset that is a multiple of a while the resulting address still violates the request. After verifying the range, derive the returned pointer from the backing region’s base pointer using the offset start - base. This keeps the pointer associated with the underlying storage.

Allocate at the cursorRound upcursorUse therequestedalignmentAddrequestedsizeCompute theexclusiveendCheck endRequire endat or belowlimitAdvancecursorSet cursorto endExit from step 3: Overflow or no spaceReturn nullReturnstartRound upcursorUse therequestedalignmentAddrequestedsizeCompute theexclusiveendCheck endRequire endat or belowlimitAdvancecursorSet cursorto endExit from step 3: Overflow orno spaceReturn nullReturnstart
Compute the aligned range before committing the next cursor

For an arithmetic example, suppose the base is aligned to sixteen bytes and the region has 32 bytes. Express each position as an offset from the base. A request for three bytes at alignment one receives offsets zero through two and leaves the cursor at offset three. A request for eight bytes at alignment eight starts at offset eight and leaves the cursor at sixteen. Offsets three through seven were skipped for alignment. The second request consumes thirteen bytes of available capacity, even though its caller receives only eight.

At offset sixteen, a request for seventeen bytes at alignment one would end at offset 33. It fails and leaves the cursor at sixteen. A request for sixteen bytes at alignment sixteen can then use the remaining space and set the cursor to 32. Once the cursor is at the limit, every subsequent nonzero request fails. These offsets follow from the example layouts and region size.

Treat reading the cursor, choosing the range, and committing the new cursor as one operation with respect to other callers. If two requests read the same cursor concurrently and both commit independently, each can receive the same storage. In the first kernel setup, the simple version can run under a boot-time restriction that allocation calls cannot overlap, including through interrupt handlers. A kernel that permits overlapping calls must synchronize the cursor update. The region’s size and alignment rules apply in either setting.

03

Release without reclaiming bytes

3 min read

A bump heap’s dealloc leaves the cursor exactly where it was. Dropping a Box<T> still runs the value’s destructor if it has one. For a nonzero-sized allocation, the box then releases the storage through the allocator. The allocation’s lifetime has ended, and any raw pointer into it must cease to be used. The allocator keeps those bytes unavailable for later requests. Ending an allocation and recovering its storage are two distinct effects.

A Vec can use the same heap. A vector with allocated capacity owns a buffer. As long as that capacity is sufficient, adding elements can use the buffer it already has. When growth requires more storage, the default GlobalAlloc::realloc implementation can request a new block, copy the retained bytes, and call dealloc on the old block on success. A bump heap that uses this default advances its cursor for the new allocation and leaves the old range unavailable. The vector uses the returned block, so this move happens as an explicit resize under the allocation contract.

The effect of releasing a blockBeforereleaseAfter releaseBlock lifetimeLiveEndedCursorAfterallocatedrangesSame addressAvailable rangeCursor tolimitCursor tolimit
After a live allocation is released, only the bytes beyond the cursor are available for the next request

Suppose the eight-byte allocation in the example is released when the cursor is at offset sixteen. The next request still begins its alignment calculation at sixteen. Releasing the earlier three-byte allocation changes nothing about the calculation either. This is why a workload can exhaust a bump heap while keeping very few objects live at once. Its capacity is consumed by all successful requests and their alignment padding, even if the associated values have already been dropped.

A bump heap is enough for bounded startup work where the total allocation demand fits in the reserved region. When evaluating whether that region is large enough, count every block allocated during startup, including replacement vector buffers, and include alignment padding. Moving the cursor backward while any affected allocation is still live could make two callers own the same bytes. A whole-region reset requires a lifetime boundary that guarantees all earlier allocations have ended. Ordinary dealloc provides no such guarantee.

The linked-list heap allocator is the next lesson. It addresses the capacity problem you can now predict from the cursor by tracking released ranges so later requests can use them.

Key takeaways

  • A successful nonzero allocation provides aligned storage that remains at the same address while the allocation is live.
  • GlobalAlloc::alloc requires a nonzero layout size, while an interface that supports successful zero-size requests can use a non-null, aligned sentinel.
  • GlobalAlloc::dealloc requires the original pointer and layout even when the allocator ignores both.
  • A bump heap consumes alignment padding and requested bytes, and individual deallocations leave the cursor unchanged.
Reflect
  1. Explain to a colleague, in two sentences: identify the caller and allocator obligations for a nonzero GlobalAlloc request
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close