knaxuslearn · build · ship

Projects / Memory allocator / Phase 4

Phase 4 of 4 · about 2.5 hours

Catch the bugs

You end with a heap that reports overflows, double frees, bad pointers, use after free and leaks.

Step 4.1: Guard bytes (about 30 minutes)

The commonest memory bug is writing a few bytes past the end of a buffer. Nothing stops you, and the damage lands in whoever lives next door. A canary is a known value placed right after your data. If it has changed when you free the block, something wrote too far. We reserve the last 8 bytes of every block for it. Change allocate to reserve room and write the canary:

  void* allocate(std::size_t n) {
    n = round_up((n < kMinPayload ? kMinPayload : n) + kCanarySize);  // room for the guard at the end
    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;
      write_canary(b);
      return b + kHeader;
    }
    return nullptr;
  }

Step 4.2: Report, don't crash (about 40 minutes)

deallocate now returns a Status instead of nothing, so the caller (or a test) can see what happened:

  Status deallocate(void* p) {
    if (p == nullptr) return Status::Ok;
    std::byte* b = static_cast<std::byte*>(p) - kHeader;
    if (!is_block_start(b)) return Status::BadPointer;
    Header* h = header(b);
    if (is_free(h)) return Status::DoubleFree;
    const bool intact = canary_ok(b);
    std::memset(b + kHeader, 0xDD, size(h));  // poison: a use after free now reads 0xDD bytes
    h->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);
    }
    return intact ? Status::Ok : Status::Overflow;
  }

  std::size_t leaked_blocks() const { return stats().used_blocks; }

It rejects pointers that are not the start of a block (BadPointer, found by walking the blocks, which is slow but fine for a debug heap), pointers whose block is already free (DoubleFree), and blocks whose canary was overwritten (Overflow). Before freeing, it fills the payload with 0xDD, so a program that reads freed memory sees an obvious pattern. The helper functions:

  // The guard sits in the last 8 bytes of the block. Writing past the end of your memory breaks it.
  void write_canary(std::byte* b) const {
    std::memcpy(b + kHeader + size(header(b)) - kCanarySize, &kCanary, kCanarySize);
  }
  bool canary_ok(std::byte* b) const {
    std::uint64_t value;
    std::memcpy(&value, b + kHeader + size(header(b)) - kCanarySize, kCanarySize);
    return value == kCanary;
  }

  // Is b really the start of a block? Walk the blocks to find out (slow, which is fine for a debug heap).
  bool is_block_start(std::byte* b) const {
    for (std::byte* x = begin_; x != nullptr; x = next(x)) {
      if (x == b) return true;
    }
    return false;
  }

Step 4.3: Break it on purpose (about 40 minutes)

Create try_bugs.cpp, which commits each bug in turn:

#include <cstdio>
#include <cstring>

#include "heap.hpp"

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

static const char* name(Heap::Status s) {
  switch (s) {
    case Heap::Status::Ok: return "ok";
    case Heap::Status::DoubleFree: return "double free";
    case Heap::Status::BadPointer: return "bad pointer";
    case Heap::Status::Overflow: return "buffer overflow";
  }
  return "?";
}

int main() {
  Heap heap(buffer, sizeof buffer);

  auto* good = static_cast<char*>(heap.allocate(100));
  std::memset(good, 'x', 100);
  std::printf("normal free:      %s\n", name(heap.deallocate(good)));

  auto* slack = static_cast<char*>(heap.allocate(100));
  std::memset(slack, 'x', 102);  // 2 bytes too many: lands in padding, nobody notices
  std::printf("2 bytes over:     %s\n", name(heap.deallocate(slack)));

  auto* over = static_cast<char*>(heap.allocate(100));
  std::memset(over, 'x', 106);  // 6 bytes too many: reaches the guard
  std::printf("heap still valid: %s\n", heap.check() ? "yes" : "no, the guard was overwritten");
  std::printf("free after overflow: %s\n", name(heap.deallocate(over)));

  auto* twice = heap.allocate(64);
  heap.deallocate(twice);
  std::printf("second free:      %s\n", name(heap.deallocate(twice)));

  int on_the_stack = 0;
  std::printf("free of a stack pointer: %s\n", name(heap.deallocate(&on_the_stack)));

  auto* stale = static_cast<unsigned char*>(heap.allocate(64));
  heap.deallocate(stale);
  std::printf("byte read after free: 0x%02X\n", stale[0]);

  heap.allocate(500);
  heap.allocate(200);
  std::printf("blocks never freed: %zu\n", heap.leaked_blocks());
}
normal free:      ok
2 bytes over:     ok
heap still valid: no, the guard was overwritten
free after overflow: buffer overflow
second free:      double free
free of a stack pointer: bad pointer
byte read after free: 0xDD
blocks never freed: 2

Read it line by line:

  • A normal free is fine.
  • Two bytes too many went unnoticed. A request for 100 bytes plus the 8-byte guard becomes 112 bytes, so bytes 100 to 103 are padding. A canary placed at the end cannot see writes that land in padding. That is a limit of this technique.
  • Six bytes too many reached the guard: check() fails and the free reports buffer overflow.
  • The second free of the same pointer is a double free, and freeing a stack address is a bad pointer.
  • A read after free returns 0xDD.
  • Two blocks were never freed, and leaked_blocks() says so.

Tools like AddressSanitizer catch the 2-byte case by putting guard zones around every allocation at exact byte boundaries. Our canary is the cheap version.

Step 4.4: Does the good path still work? (about 40 minutes)

Safety features must not break normal use. Run the stress test against the new heap. This version checks the return value of every free:

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

#include "heap.hpp"

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

int main() {
  Heap heap(buffer, sizeof buffer);
  std::mt19937 rng(7);
  std::vector<std::pair<unsigned char*, std::size_t>> live;
  std::size_t bad = 0, invalid = 0;

  for (int step = 0; step < 200000; step++) {
    if (live.empty() || rng() % 100 < 55) {
      const std::size_t size = 1 + rng() % 300;
      auto* p = static_cast<unsigned char*>(heap.allocate(size));
      if (p) {
        std::memset(p, 0xAB, size);  // stays inside the request
        live.push_back({p, size});
      }
    } else {
      const std::size_t i = rng() % live.size();
      if (heap.deallocate(live[i].first) != Heap::Status::Ok) bad++;
      live[i] = live.back();
      live.pop_back();
    }
    if (step % 1000 == 0 && !heap.check()) invalid++;
  }
  for (auto& l : live) heap.deallocate(l.first);
  std::printf("frees that reported a problem: %zu\n", bad);
  std::printf("layout checks that failed:     %zu\n", invalid);
  std::printf("blocks never freed:            %zu\n", heap.leaked_blocks());
}
frees that reported a problem: 0
layout checks that failed:     0
blocks never freed:            0

No free reported a problem, the layout was valid every time (now including a canary check on every used block) and nothing leaked. We also compiled both stress tests with -fsanitize=address,undefined and they ran clean. A caveat: our heap lives in one big static buffer, so AddressSanitizer cannot see inside it. It would find a bug in the allocator's own code, such as a read outside the buffer, but not an overflow from one block into the next. That is why we built the canaries.

Phase 4 done

You wrote about 200 lines of heap, 90 lines of pool and a handful of tests, and you can now explain what happens behind new.