xtc_mctx(3)

---

xtc_mctx(3)

hierarchical memory contexts with cleanup callbacks

XTC_MCTX(3) Library Functions Manual XTC_MCTX(3)

xtc_mctx_create, xtc_mctx_destroy, xtc_mctx_alloc, xtc_mctx_calloc, xtc_mctx_strdup, xtc_mctx_free, xtc_mctx_register_cleanup, xtc_mctx_name, xtc_mctx_total_bytes, xtc_mctx_total_chunks, xtc_mctx_resethierarchical memory contexts with cleanup callbacks

#include <xtc.h>
#include <xtc_mctx.h>

int
xtc_mctx_create(xtc_mctx_t *parent, const char *name, xtc_mctx_t **out);

void
xtc_mctx_destroy(xtc_mctx_t *ctx);

void *
xtc_mctx_alloc(xtc_mctx_t *ctx, size_t size);

void *
xtc_mctx_calloc(xtc_mctx_t *m, size_t n, size_t size);

void *
xtc_mctx_strdup(xtc_mctx_t *m, const char *s);

void
xtc_mctx_free(xtc_mctx_t *m, void *p);

int
xtc_mctx_register_cleanup(xtc_mctx_t *m, xtc_mctx_cleanup_fn fn, void *user);

const char *
xtc_mctx_name(const xtc_mctx_t *m);

size_t
xtc_mctx_total_bytes(const xtc_mctx_t *m);

size_t
xtc_mctx_total_chunks(const xtc_mctx_t *m);

void
xtc_mctx_reset(xtc_mctx_t *ctx);

xtc_mctx is a hierarchical memory context, modeled on PostgreSQL's MemoryContext. Allocations belong to a context; destroying the context bulk-frees everything in it (plus all child contexts recursively). Useful for request-scoped memory: create a context per request, allocate freely, destroy at the end without tracking individual frees.

Each context can register cleanup callbacks fired on destroy (before the bulk-free) to release non-memory resources.

() returns raw memory within the context; () zeroes an n by size array; and () copies string s into the context. All live until the context is reset or destroyed. () optionally releases a single allocation early. () adds a callback fn run in LIFO order at reset/destroy.

() returns the context's name; () and () report the memory and chunk count currently charged to the context.

xtc_mctx_t *root, *req;
xtc_mctx_create(NULL, "root", &root);
xtc_mctx_create(root, "request-42", &req);

/* Allocate request-scoped objects. */
char *buf = xtc_mctx_alloc(req, 4096);
struct widget *w = xtc_mctx_alloc(req, sizeof *w);

/* Done; bulk-free everything in req. */
xtc_mctx_destroy(req);

xtc_slab(3), xtc_res(3), xtc(7)

Appeared in xtc 0.1.

May 28, 2026 Debian

View the mdoc source