</>EmbeddedInterview

How do you detect a double free or an invalid free in your own allocator?

Medium"Coding: Memory & String Functions"
#include <stdint.h>
#include <stddef.h>

#define MAGIC_USED 0xA110C8EDu
#define MAGIC_FREE 0xF4EEF4EEu

typedef struct hdr { uint32_t magic; uint32_t size; } hdr_t;

extern uint8_t heap[], heap_end[];
void fault(const char *why);

void checked_free(void *p)
{
    if (p == NULL) return;
    hdr_t *h = (hdr_t *)p - 1;
    if ((uint8_t *)h < heap || (uint8_t *)p >= heap_end) { fault("free: not a heap pointer"); return; }
    if (h->magic == MAGIC_FREE) { fault("double free"); return; }
    if (h->magic != MAGIC_USED) { fault("free: corrupted header or bad pointer"); return; }
    h->magic = MAGIC_FREE;
    /* ... return block to the free list, optionally fill with 0xDD to catch use-after-free ... */
}

Techniques: a magic number in each block header (used/free), range checks against the heap bounds, a trailing canary word after each block checked on free (detects overruns), poisoning freed memory with a pattern (use-after-free shows up as 0xDDDDDDDD values), and for pools a bitmap of allocated blocks. On Linux, AddressSanitizer and glibc's own checks (free(): double free detected in tcache 2) do this automatically.