Neither free
nor delete
nor delete []
work with stack-allocated memory.
The rule is actually ridiculously simple:
- Every
malloc
must be paired with exactly onefree
, and vice-versa.1 - Every
new
must be paired with exactly onedelete
, and vice-versa. - Every
new []
must be paired with exactly onedelete []
, and vice-versa.
The end.
1 Okay, I lied. malloc
/free
is harder, because there’s also calloc
and realloc
. Here’s the amended rule:
- Every
malloc
orcalloc
must be paired with exactly one call tofree
orrealloc
. - Every
realloc
that does not free memory must be paired with exactly one call tofree
orrealloc
. - (Vice-versa: Every
free
must belong to exactly one call made tomalloc
,calloc
orrealloc
.)
In other words, calloc
behaves like malloc
(for the sake of memory allocation). realloc
is an inclusive intermediate link of the malloc
→ free
chain – it can replace both malloc
and free
, and it can be put in between such calls.