← Back to work

TypeScript · VS Code Extension API · 2025 · solo

C Memory Police

A VS Code extension that catches memory leaks, double frees, and the classic failed-realloc leak — live, as you type.

The extension running in VS Code, flagging potential leaks, invalid frees, and a bad realloc inline, with a hover explaining a double free.
500 ms
reanalysis debounce

The problem

C’s memory bugs — a malloc with no matching free, a double free, a realloc result nobody checked before overwriting the original pointer — are exactly the kind of mistake that’s obvious in hindsight and easy to miss while actually writing the code. Catching them later, in a debugger or a leak detector, means the context for why the allocation happened is already gone.

The approach

On every file open, save, editor switch, or 500ms-debounced keystroke, the extension re-parses the open C file with a lightweight brace-counting function parser — regex-based, not a full C compiler front end — and scans each function body for malloc/calloc/realloc calls against their matching free() calls. Unmatched allocations become leak warnings. Pointers freed twice, freed after being invalidated by realloc, or already freed become “invalid free” errors. And the specific ptr = realloc(ptr, ...) pattern — where a failed realloc overwrites the only reference to the original block — gets its own “bad realloc” warning recommending a temporary pointer instead. Each category gets its own color and a hover explanation with a suggested fix.

What was hard

Two things past matching a malloc to a free. First, a pointer freed under a different name than it was allocated with (void *tmp = buf; free(tmp);) needed alias-chain resolution — the analyzer walks backward through assignments, up to ten hops, to find which allocation a freed variable actually traces back to. Second, catching leaks that only happen on some paths: a function that allocates, then returns early on an error condition before reaching its free() call, without also flagging the completely normal pattern of checking for allocation failure (if (!ptr) return NULL;) as a leak — the analyzer looks for a null-check on the variable in the few lines before a suspect early return before deciding it’s actually a bug.

Result

Leak, double-free, invalid-free, and bad-realloc warnings appear inline as you write C, each with a specific explanation, instead of surfacing later as a crash or a valgrind report with the original context long gone.