knaxuslearn · build · ship

Projects / Memory allocator / Phase 1

Phase 1 of 4 · about 2.5 hours

The arena

You end with an allocator you can explain in one sentence, measured against new.

First, what is memory allocation? A program asks "give me 40 bytes" and gets back an address it can use. Later it says "I am done with that address". An allocator is the bookkeeping that makes those two calls work. The simplest possible bookkeeping is a single number: how much of a big buffer we have used so far.

Step 1.1: Hand out the next bytes (about 30 minutes)

Create arena.hpp. An arena owns a block of memory and gives out the next unused piece each time. It never frees one piece alone, because it does not remember where pieces start. It can only drop everything at once.

#pragma once
#include <cstddef>
#include <cstdint>

// The simplest allocator there is: hand out the next free bytes, never free one by one.
class Arena {
 public:
  Arena(void* buffer, std::size_t size) : base_(static_cast<std::byte*>(buffer)), size_(size) {}

  void* alloc(std::size_t size, std::size_t align = alignof(std::max_align_t)) {
    // align must be a power of two: 1, 2, 4, 8, 16, ...
    const auto start = reinterpret_cast<std::uintptr_t>(base_) + used_;
    const auto aligned = (start + align - 1) & ~(static_cast<std::uintptr_t>(align) - 1);
    const auto offset = aligned - reinterpret_cast<std::uintptr_t>(base_);
    if (offset + size > size_) return nullptr;  // out of space
    used_ = offset + size;
    return base_ + offset;
  }

  void reset() { used_ = 0; }  // "free" everything at once
  std::size_t used() const { return used_; }
  std::size_t capacity() const { return size_; }

 private:
  std::byte* base_;
  std::size_t size_;
  std::size_t used_ = 0;
};

Walk through alloc:

  • start is the first unused address.
  • aligned rounds it up so the address is a multiple of align. We come back to why in the next step.
  • offset is how far into the buffer that is. If the request does not fit, we return nullptr.
  • Otherwise we remember the new used_ and return the address.

reset sets used_ back to zero, which is how an arena "frees": all at once, in one assignment.

Step 1.2: Alignment, the part that bites (about 40 minutes)

Many CPUs read a double fastest, or only, from an address that is a multiple of 8. A type's alignment is the multiple it needs, and alignof(T) tells you. An allocator that ignores it hands out addresses that are slow at best and crash at worst (and are undefined behaviour in C++, which means the compiler may assume it never happens).

The line (start + align - 1) & ~(align - 1) rounds start up to the next multiple of align. It works only when align is a power of two, which every real alignment is. Try some numbers by hand: with align = 8 and start = 13, we get (13 + 7) & ~7, which is 20 & ~7, which is 16.

Create try_arena.cpp. It allocates a char, then a double, then an int, and prints where each landed:

#include <cstdio>

#include "arena.hpp"

alignas(64) static std::byte buffer[1024];

int main() {
  Arena arena(buffer, sizeof buffer);

  auto* c = static_cast<char*>(arena.alloc(1, 1));
  auto* d = static_cast<double*>(arena.alloc(sizeof(double), alignof(double)));
  auto* i = static_cast<int*>(arena.alloc(sizeof(int), alignof(int)));

  std::printf("char   at offset %2td\n", reinterpret_cast<std::byte*>(c) - buffer);
  std::printf("double at offset %2td  (multiple of 8: %s)\n", reinterpret_cast<std::byte*>(d) - buffer,
              reinterpret_cast<std::uintptr_t>(d) % 8 == 0 ? "yes" : "no");
  std::printf("int    at offset %2td\n", reinterpret_cast<std::byte*>(i) - buffer);
  std::printf("used %zu of %zu bytes\n", arena.used(), arena.capacity());

  void* big = arena.alloc(2000);
  std::printf("2000 bytes: %s\n", big ? "ok" : "nullptr (full)");
  arena.reset();
  std::printf("after reset, used %zu\n", arena.used());
}
char   at offset  0
double at offset  8  (multiple of 8: yes)
int    at offset 16
used 20 of 1024 bytes
2000 bytes: nullptr (full)
after reset, used 0

The char took byte 0. The double could not go at byte 1, so it skipped to 8. The int followed at 16. Twenty bytes were used (the padding counts). A request that does not fit gets nullptr, and reset brings us back to zero.

Step 1.3: How fast is "one assignment"? (about 40 minutes)

Create try_speed.cpp. It builds a linked list of two million nodes with new and frees them one by one, then builds the same list in an arena and frees it with one reset:

#include <chrono>
#include <cstdio>
#include <vector>

#include "arena.hpp"

struct Node {
  long value;
  Node* next;
};

template <typename F>
double seconds(F&& run) {
  const auto start = std::chrono::steady_clock::now();
  run();
  return std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
}

int main() {
  constexpr int kNodes = 2'000'000;
  long sink = 0;

  const double with_new = seconds([&] {
    Node* head = nullptr;
    for (int i = 0; i < kNodes; i++) head = new Node{i, head};
    for (Node* n = head; n; n = n->next) sink += n->value;
    while (head) {
      Node* next = head->next;
      delete head;
      head = next;
    }
  });

  std::vector<std::byte> storage(kNodes * sizeof(Node));
  const double with_arena = seconds([&] {
    Arena arena(storage.data(), storage.size());
    Node* head = nullptr;
    for (int i = 0; i < kNodes; i++) head = new (arena.alloc(sizeof(Node), alignof(Node))) Node{i, head};
    for (Node* n = head; n; n = n->next) sink += n->value;
    arena.reset();
  });

  std::printf("new/delete  %.3f s\n", with_new);
  std::printf("arena       %.3f s   (%.1fx faster)\n", with_arena, with_new / with_arena);
  return sink < 0;  // uses sink so the loops are not optimised away
}
new/delete  0.067 s
arena       0.009 s   (7.7x faster)

Several times faster on this machine, and your ratio will differ. The arena does almost nothing per call (one add, one compare), and freeing is free. new has to find a block, keep records and merge on delete. The line new (arena.alloc(...)) Node{...} is placement new: it builds an object at an address you choose instead of asking for memory.

Step 1.4: When an arena is the right tool (about 40 minutes)

An arena shines when many objects share one lifetime: everything allocated while handling one web request, one frame of a game, one compile step. You drop them all together. It is the wrong tool when objects die at different times, because memory is only reclaimed on reset. A long-lived program that allocates and frees different things all day would run out.

Pitfall: objects with destructors. reset does not call them. If a node owns a file or a lock, the arena will not close it. Arena allocation is for plain data, or you run the destructors yourself first.

Think it through: you want to remove one node from the middle of the list. What would the arena need to remember to let you do that? That question is the next phase.

Phase 1 done

An arena is a pointer that only moves forward. Now we build the allocator that can free one thing at a time.