From 21st-Century C:
The easiest way to avoid bugs related to malloc is not to use malloc.
and
Production code tends to have few uses of malloc, typically wrapped in new/copy/free functions so the main code doesn’t have to deal further with memory management.
Primary Question: Can someone provide a super simple, idiomatic example of how one might use function wrappers like this to subvert the direct usage of free
and malloc
?
Secondary Question (Optional): In particular, can the clever use of such functions emulate the behavior (or even some of the behavior) of the C++ shared_ptr
and unique_ptr
? That is, can using such functions free you from the worry that you might accidently free dangling pointers and/or create leaks? Or is that simply impossible in C, even with the use of such functions?