Lesson 5 of 8
Memory Safety Audit & const Correctness Checklist
Before shipping a C project, perform a systematic memory safety and const correctness audit. This section provides the full checklist with before/after examples for common issues found in real C codebases.
Production Safety Checklist - Audit Every Function
Production Safety Checklist - Audit Every Function
/* Memory Safety & const-Correctness Production Audit
═══════════════════════════════════════════════════════
CONST CORRECTNESS CHECKLIST
═══════════════════════════════════════════════════════
☐ Every function that doesn't modify its input
uses const pointers:
BAD: void print_task(Task *t)
GOOD: void print_task(const Task *t)
BAD: int find_by_id(TaskList *tl, uint32_t id)
GOOD: Task *find_by_id(const TaskList *tl, uint32_t id)
☐ String parameters that are read-only:
BAD: int store_load(char *path, ...)
GOOD: int store_load(const char *path, ...)
☐ Enum/struct parameters passed by value for small types:
OK: void set_priority(Task *t, Priority p) // p is by value
═══════════════════════════════════════════════════════
MEMORY MANAGEMENT CHECKLIST
═══════════════════════════════════════════════════════
☐ Every malloc/calloc has a NULL check?
if (!ptr) { perror("..."); goto cleanup; }
☐ Every allocation has exactly one matching free?
☐ free() followed immediately by = NULL?
free(tl->data); tl->data = NULL;
☐ No double-free?
free(NULL) is safe - use it.
☐ realloc uses a temp pointer?
void *tmp = realloc(p, n);
if (!tmp) { free(p); return -1; }
p = tmp;
☐ No return without freeing all allocations?
→ Use goto cleanup pattern.
☐ No stack arrays larger than ~64KB?
→ Use malloc for big buffers.
☐ No returning pointer to local variable?
BAD: int *f(void) { int x = 5; return &x; }
═══════════════════════════════════════════════════════
STRING SAFETY CHECKLIST
═══════════════════════════════════════════════════════
☐ All buffer writes use size-limited functions?
strncpy(dst, src, sizeof(dst)-1); dst[sizeof(dst)-1] = '