Memory api misuse

From thejefflarson/soundcheck · View interactive version

Memory api misuse is an AI agent skill from the GitHub repository thejefflarson/soundcheck. Detects function-local misuse of memory and resource APIs in C, C++, and Rust unsafe — allocations whose return value is not checked, frees on error paths that race the success path, locks initialized incorrectly, file descriptors leaked across exec. Use when writing or modifying C or C++ code that

How to use this skill

Skill file

Memory API Misuse (CWE-690, CWE-415, CWE-401)

What this checks

C, C++, and Rust unsafe memory and resource APIs called incorrectly at a single call

site — a NULL return dereferenced, a double-free on an error path, a lock used

before init, a file descriptor that survives exec(). Existing static analyzers

catch the easy cases; this skill targets the ones that read clean on first pass but

fail in error or cleanup paths. It does local pattern matching at the call site,

not whole-program lifetime analysis (that's the job of TSAN, ASAN, Valgrind, and the

Rust borrow checker).

Vulnerable patterns

Fix immediately

Flag the vulnerable call site and rewrite it so the API return value is checked and

cleanup runs exactly once per allocation. Establish these properties:

  1. Every allocation return is checked before use. A NULL or MAP_FAILED return

turns into a controlled error path — never a silent dereference.

  1. realloc results land in a temporary first. The original pointer remains

valid on failure so the caller can free it deterministically; the original

pointer is overwritten only after success is confirmed.

  1. Allocation cleanup has a single owner per path. Use one cleanup label, one

RAII wrapper, or one defer/scope_exit — never free the same allocation

on both an error branch and a shared cleanup path.

  1. Synchronization primitives are initialized before first use. A static

initializer macro at declaration or a documented init call before the first

lock — never used uninitialized.

  1. File descriptors that should not cross exec() are opened close-on-exec.

Use the close-on-exec mode flag at open time, not a follow-up fcntl race.

  1. Freed pointers are nulled at the same call site so subsequent reads fault

loudly instead of silently using freed memory.

Translate these principles to the specific allocator, lock, and fd API of the

audited file. Use the platform's documented safe forms — do not invent variants.

Verification

After rewriting, confirm:

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.