malloc, realloc & free in C
From the C cheat sheet · Dynamic Memory · verified Jul 2026
malloc, realloc & free
Allocate, resize, and release memory.
c
// Quick Reference
#include <stdlib.h>
int *p = malloc(n * sizeof *p);
if (!p) { /* handle */ }
free(p);
p = nullptr;💡 sizeof *p (deref) is safer than sizeof(int) - it tracks the pointer's type automatically.
⚡ Always check malloc/realloc for NULL before using the result.
📌 Match every malloc/calloc with exactly one free - unfreed memory is a leak.
🟢 Set a pointer to nullptr after free to avoid use-after-free and double-free bugs.
memorymalloc