Additional projects

defer.h

C functions with multiple exits can repeat or miss cleanup.

A single header uses the GNU/Clang cleanup attribute to run registered callbacks at normal lexical scope exit.

DevelopmentMITC99
Last verified
Not audited against current README/docs
Platform scope
Portable C99; integration depends on caller-provided adapters

What it solves

C functions with multiple exits can repeat or miss cleanup.

How it works

1Resource acquisition2scope guard3work4lexical cleanup

Use it when

Free a buffer on every normal return path
Close a hosted FILE at scope exit
Dismiss cleanup after ownership transfer

Quick Start

#define DEFER_ENABLE_FREE_HELPER
#include "defer.h"
char *buf=malloc(128);
if(buf==NULL) return;
DEFER_FREE(buf);
/* Expected: free runs on normal scope exit. */

Engineering evidence

  • Examples and tests cover the documented GNU/Clang cleanup-attribute path

Known limits

  • Pure MSVC is unsupported unless an explicit no-op fallback is enabled
  • Cleanup does not run on longjmp, abort, process termination, reset, hard fault or power loss
  • Cleanup callbacks cannot propagate errors