← ClaudeAtlas

memory-contextslisted

Allocate memory in PostgreSQL backend C — pick the right MemoryContext and use palloc / palloc0 / pstrdup / psprintf correctly. Covers CurrentMemoryContext / TopMemoryContext / per-query / per-tuple / ExecutorState context choice, MemoryContextSwitchTo discipline, the OOM-throws-ereport contract (no NULL checks), pfree vs MemoryContextReset vs MemoryContextDelete, the AllocSet vs Slab vs Generation vs Bump context-type cheat sheet, and leak-scoping in long-running backends. Use whenever a PG patch or extension calls palloc / palloc0 / MemoryContextAlloc, creates or switches a MemoryContext, picks AllocSet vs Slab vs Generation vs Bump, or debugs a context-shaped leak. Skip for plain malloc / free / jemalloc / mimalloc / tcmalloc, JVM / Go / .NET GC tuning, Rust Box / Rc / Arc / lifetimes, shared_buffers / work_mem production tuning, valgrind / heaptrack on non-PG programs, and C++ smart pointers.
matejformanek/postgres-claude · ★ 0 · AI & Automation · score 70
Install: claude install-skill matejformanek/postgres-claude
# Memory contexts — actionable rules Reference doc: `knowledge/idioms/memory-contexts.md`. ## Allocation cheat sheet - `palloc(n)` — allocate in `CurrentMemoryContext`. **Never returns NULL** — it calls `ereport(ERROR)` on OOM. Don't test for NULL. - `palloc0(n)` — like palloc plus zero-fill. - `pstrdup(s)` / `pnstrdup(s, n)` / `psprintf(fmt, ...)` — string variants. - `palloc_object(T)`, `palloc_array(T, count)`, `palloc0_array(T, count)` — type-safe macros. Prefer these over raw size calculations. - `palloc_extended(n, MCXT_ALLOC_NO_OOM)` — opt out of the OOM-throws contract (returns NULL on failure). Use only when you specifically can recover. - `palloc_extended(n, MCXT_ALLOC_HUGE)` / `MemoryContextAllocHuge` — past the `MaxAllocSize` (≈1 GB) limit; capped at `MaxAllocHugeSize` (SIZE_MAX/2). - `MemoryContextAlloc(ctx, n)` — allocate in a specific context without switching `CurrentMemoryContext`. - `repalloc(p, n)` — grow/shrink. Goes to p's original context, not current. - `pfree(p)` — free a chunk. Goes to its original context. ### Hard rules - **`pfree(NULL)` is undefined** — always check first if pointer may be NULL. - **`repalloc(NULL, n)` is undefined** — first allocation must be `palloc`. - **`palloc(0)` is legal** — returns a usable chunk. - **Do not test palloc's return for NULL** unless you used `MCXT_ALLOC_NO_OOM`. - **Single-allocation cap is `MaxAllocSize` (1 GB - 1)** for regular palloc. Exceeding it raises `errmsg("invalid memory alloc reques