Example 1 — Counting live allocations with wrappers
A tiny counter makes leaks visible without external tools.
#include <stdio.h>
#include <stdlib.h>
static int live = 0;
static void *xmalloc(size_t n) { live++; return malloc(n); }
static void xfree(void *p) { if (p) live--; free(p); }
int main(void) {
int *a = xmalloc(sizeof *a);
int *b = xmalloc(sizeof *b);
printf("live allocations: %d\n", live);
xfree(a);
printf("after freeing a: %d\n", live);
xfree(b);
printf("after freeing b: %d\n", live);
return 0;
} How It Works
- Each wrapped allocation increments
live; each free decrements it. - Anything above 0 at exit is a leak.
- Real projects use sanitizers instead of hand-written counters.
