knaxuslearn · build · ship

Projects / Memory allocator / Phase 2

Phase 2 of 4 · about 2.5 hours

A heap that frees

You end with allocate and deallocate for any size, with a checker that proves the layout is valid, and a measured fragmentation problem.

Step 2.1: Blocks with headers (about 50 minutes)

To free one piece we must know how big it is and where it ends. The classic answer: put a small header right before each piece. The buffer becomes a row of blocks, each with a header and some payload:

| header | payload ... | header | payload ... | header | payload ... |
   16 B      N bytes      16 B      M bytes

The header holds the payload size, a flag for "this block is free", and the size of the block before it (so we can walk backwards later). Walking forward is current + header + size. All sizes are multiples of 16, so the lowest bit of the size is always zero and we can use it as the free flag. Create heap.hpp. The first part is the public side: setup, allocate and deallocate.

  Heap(void* buffer, std::size_t bytes) {
    begin_ = static_cast<std::byte*>(buffer);
    end_ = begin_ + (bytes / kAlign) * kAlign;
    auto* first = header(begin_);
    first->size_and_flag = (static_cast<std::size_t>(end_ - begin_) - kHeader) | kFree;
    first->prev_size = 0;
  }

  void* allocate(std::size_t n) {
    n = round_up(n < kMinPayload ? kMinPayload : n);
    for (std::byte* b = begin_; b != nullptr; b = next(b)) {
      Header* h = header(b);
      if (!is_free(h) || size(h) < n) continue;  // first fit: take the first block that is big enough
      split(b, n);
      h->size_and_flag &= ~kFree;
      return b + kHeader;
    }
    return nullptr;
  }

  void deallocate(void* p) {
    if (p == nullptr) return;
    std::byte* b = static_cast<std::byte*>(p) - kHeader;
    header(b)->size_and_flag |= kFree;
    // merge with the block after, then with the block before
    if (std::byte* n = next(b); n != nullptr && is_free(header(n))) merge(b, n);
    if (header(b)->prev_size != 0) {
      std::byte* p2 = b - kHeader - header(b)->prev_size;
      if (is_free(header(p2))) merge(p2, b);
    }
  }

Read allocate first:

  • It rounds the request up to a multiple of 16 (at least 16).
  • It walks the blocks from the start and takes the first free block that is big enough. This strategy is called first fit.
  • split cuts the block in two when there is enough left over to be a useful block of its own.
  • It clears the free flag and returns the address just after the header.

The private helpers it uses:

 private:
  struct Header {
    std::size_t size_and_flag;  // payload size; the lowest bit says "free"
    std::size_t prev_size;      // payload size of the block before, 0 for the first block
  };
  static constexpr std::size_t kHeader = sizeof(Header);  // 16 bytes
  static constexpr std::size_t kAlign = 16;
  static constexpr std::size_t kMinPayload = 16;
  static constexpr std::size_t kFree = 1;

  static std::size_t round_up(std::size_t n) { return (n + kAlign - 1) & ~(kAlign - 1); }
  static Header* header(std::byte* b) { return reinterpret_cast<Header*>(b); }
  static const Header* header(const std::byte* b) { return reinterpret_cast<const Header*>(b); }
  static bool is_free(const Header* h) { return (h->size_and_flag & kFree) != 0; }
  static std::size_t size(const Header* h) { return h->size_and_flag & ~kFree; }

  std::byte* next(std::byte* b) const {
    std::byte* n = b + kHeader + size(header(b));
    return n < end_ ? n : nullptr;
  }

  // Cut the free block at b into a block of n bytes plus a smaller free block, if the rest is worth keeping.
  void split(std::byte* b, std::size_t n) {
    Header* h = header(b);
    const std::size_t rest = size(h) - n;
    if (rest < kHeader + kMinPayload) return;  // too small to be a block: hand out the whole thing
    h->size_and_flag = n | (h->size_and_flag & kFree);
    std::byte* r = b + kHeader + n;
    header(r)->size_and_flag = (rest - kHeader) | kFree;
    header(r)->prev_size = n;
    if (std::byte* after = next(r)) header(after)->prev_size = size(header(r));
  }

  // Join block b with the block right after it (b2), which must be free.
  void merge(std::byte* b, std::byte* b2) {
    Header* h = header(b);
    h->size_and_flag = (size(h) + kHeader + size(header(b2))) | kFree;
    if (std::byte* after = next(b)) header(after)->prev_size = size(h);
  }

  std::byte* begin_;
  std::byte* end_;
};

split creates a new free block in the remainder and fixes the next block's prev_size. If the leftover is too small for a header and a minimum payload, we hand out the whole block: a little waste is better than an unusable sliver.

Step 2.2: Free, and merge the neighbours (about 40 minutes)

Look at deallocate in the listing above. It sets the free flag and then merges with the free blocks on either side. Merging, or coalescing, matters: without it, freeing two neighbouring 100-byte blocks leaves two 100-byte holes, and a 200-byte request fails even though 200 contiguous bytes are free. Merging with the next block is easy (add its size plus a header). Merging with the previous one needs the prev_size field, because we have no other way to step backwards.

Create try_basic.cpp, which prints the state after each step. check() is explained in 2.4, for now it just says whether the layout is valid:

#include <cstdio>

#include "heap.hpp"

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

static void show(const char* when, const Heap& heap) {
  const auto s = heap.stats();
  std::printf("%-16s used %zu blocks (%4zu B)   free %zu blocks (%4zu B)   valid: %s\n", when, s.used_blocks,
              s.used_bytes, s.free_blocks, s.free_bytes, heap.check() ? "yes" : "NO");
}

int main() {
  Heap heap(buffer, sizeof buffer);
  show("start", heap);

  void* a = heap.allocate(100);
  void* b = heap.allocate(200);
  void* c = heap.allocate(50);
  show("after 3 allocs", heap);
  std::printf("a is 16-aligned: %s\n", reinterpret_cast<std::uintptr_t>(a) % 16 == 0 ? "yes" : "no");

  heap.deallocate(b);
  show("freed b", heap);
  heap.deallocate(a);
  show("freed a", heap);
  heap.deallocate(c);
  show("freed c", heap);
}
start            used 0 blocks (   0 B)   free 1 blocks (1008 B)   valid: yes
after 3 allocs   used 3 blocks ( 384 B)   free 1 blocks ( 576 B)   valid: yes
a is 16-aligned: yes
freed b          used 2 blocks ( 176 B)   free 2 blocks ( 784 B)   valid: yes
freed a          used 1 blocks (  64 B)   free 2 blocks ( 912 B)   valid: yes
freed c          used 0 blocks (   0 B)   free 1 blocks (1008 B)   valid: yes

Follow the numbers. At the start there is one free block of 1008 bytes (1024 minus one 16-byte header). Three allocations of 100, 200 and 50 bytes use 112, 208 and 64 bytes after rounding, which is 384. Freeing b leaves two free blocks (the hole and the tail). Freeing a merges with the hole to its right. Freeing c merges everything back into a single block of 1008 bytes.

Step 2.3: Fragmentation (about 30 minutes)

Merging cannot fix everything. If the live blocks are scattered, the free space is chopped into pieces that are each too small. This is external fragmentation. Create try_fragment.cpp. It fills the heap with 100-byte blocks, frees every second one, and asks for a bigger block:

#include <cstdio>
#include <vector>

#include "heap.hpp"

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

int main() {
  Heap heap(buffer, sizeof buffer);
  std::vector<void*> blocks;
  while (void* p = heap.allocate(100)) blocks.push_back(p);
  std::printf("filled the heap with %zu blocks of 100 bytes\n", blocks.size());

  for (std::size_t i = 0; i < blocks.size(); i += 2) heap.deallocate(blocks[i]);  // free every other one
  const auto s = heap.stats();
  std::printf("free: %zu bytes in %zu pieces, largest piece %zu bytes\n", s.free_bytes, s.free_blocks,
              s.largest_free);
  std::printf("allocate(1000): %s\n", heap.allocate(1000) ? "ok" : "fails, although plenty of bytes are free");
  std::printf("allocate(100):  %s\n", heap.allocate(100) ? "ok" : "fails");

  for (std::size_t i = 1; i < blocks.size(); i += 2) heap.deallocate(blocks[i]);  // free the rest
  std::printf("after freeing all: %zu free piece(s), valid: %s\n", heap.stats().free_blocks,
              heap.check() ? "yes" : "NO");
}
filled the heap with 512 blocks of 100 bytes
free: 28672 bytes in 256 pieces, largest piece 112 bytes
allocate(1000): fails, although plenty of bytes are free
allocate(100):  ok
after freeing all: 1 free piece(s), valid: yes

Half the heap is free, but it is in 256 separate pieces of 112 bytes, so a 1000-byte request fails. Another 100-byte request still works. Free the rest and everything merges back into one piece. Real allocators fight this with size classes, placement policies and, in some languages, by moving objects (a compacting garbage collector). Ours just reports it.

Step 2.4: Prove it with a stress test (about 30 minutes)

A heap bug does not crash where it happens. It corrupts something, and the program dies later somewhere unrelated. So we test hard, and we give the heap a way to check itself. check() walks every block and verifies four rules: sizes are multiples of 16, each prev_size matches the block before, no two free blocks sit side by side (they would have been merged), and the sizes add up to the whole buffer.

Create try_stress.cpp. It does 300,000 random allocations and frees. Every block is filled with its own byte pattern when allocated and verified before it is freed, so any overlap between blocks shows up as a changed byte:

#include <cstdio>
#include <random>
#include <vector>

#include "heap.hpp"

alignas(16) static std::byte buffer[1 << 20];

struct Live {
  unsigned char* ptr;
  std::size_t size;
  unsigned char pattern;
};

int main() {
  Heap heap(buffer, sizeof buffer);
  std::mt19937 rng(42);
  std::vector<Live> live;
  std::size_t allocs = 0, frees = 0, failures = 0, corrupted = 0, invalid = 0;

  for (int step = 0; step < 300000; step++) {
    if (live.empty() || (rng() % 100 < 55)) {
      const std::size_t size = 1 + rng() % 400;
      auto* p = static_cast<unsigned char*>(heap.allocate(size));
      if (!p) { failures++; continue; }
      const auto pattern = static_cast<unsigned char>(rng());
      std::memset(p, pattern, size);
      live.push_back({p, size, pattern});
      allocs++;
    } else {
      const std::size_t i = rng() % live.size();
      const Live l = live[i];
      for (std::size_t k = 0; k < l.size; k++) if (l.ptr[k] != l.pattern) { corrupted++; break; }
      heap.deallocate(l.ptr);
      live[i] = live.back();
      live.pop_back();
      frees++;
    }
    if (step % 1000 == 0 && !heap.check()) invalid++;
  }
  for (const Live& l : live) heap.deallocate(l.ptr);

  std::printf("allocs %zu, frees %zu, out of memory %zu\n", allocs, frees, failures);
  std::printf("blocks whose contents changed: %zu\n", corrupted);
  std::printf("heap layout checks failed: %zu\n", invalid);
  const auto s = heap.stats();
  std::printf("at the end: %zu free piece(s), %zu used\n", s.free_blocks, s.used_blocks);
}
allocs 140167, frees 135020, out of memory 24813
blocks whose contents changed: 0
heap layout checks failed: 0
at the end: 1 free piece(s), 0 used

No block ever changed under us, check() never failed, and at the end everything had merged back into one free piece. Out-of-memory results are normal here: the test asks for more than fits sometimes, and allocate returns nullptr as it should. Compile it once more with -fsanitize=undefined and run it. Our run reported nothing, which means no misaligned access or signed overflow.

What this does not prove: it is a single-threaded test with a fixed random seed. A real allocator also needs tests with many threads and with odd sizes (zero, huge).

Phase 2 done

You have a working heap. It is also slow, and Phase 3 shows why.