C Collections

ccollections · Section 3

ccol_scoped_ptr_mp

ccol_scoped_ptr_mp - declare a raw pointer that a custom allocator frees automatically at scope exit

C Collections (libccollections, -lccollections)

#include <ccollections/common.h>
 
ccol_scoped_ptr_mp(name, type, mmgmt_procs);

Declares "type *name", sets it to NULL and registers an automatic
cleanup with __attribute__((cleanup(...))). You assign to name as usual,
with memory that mmgmt_procs->free accepts, which normally means
mmgmt_procs->malloc(size), or malloc(size) when mmgmt_procs is NULL.
 
At the end of the enclosing scope the value that name holds is freed
with mmgmt_procs->free, or with the default allocator if mmgmt_procs is
NULL.
 
This is the custom-allocator form of ccol_scoped_ptr(). That page covers
the default-allocator form and the warnings that apply to both macros,
about giving name a new value inside the scope and about releasing the
ownership with ccol_scoped_ptr_release().

name          The name of the pointer variable to declare
type          The type that the pointer points to (for example char,
              struct foo)
mmgmt_procs   The custom allocator (ccol_memmgmt_procs *) that frees
              the last value of name, or NULL for the default allocator

Needs GCC or Clang, because it uses __attribute__((cleanup)).
 
The macro keeps a reference to mmgmt_procs instead of a copy, so
mmgmt_procs must stay valid for at least as long as the enclosing scope
of name. That always holds when mmgmt_procs is a variable already in
scope at the declaration, which is the common case.
 
The cleanup tests mmgmt_procs for NULL to choose between
mmgmt_procs->free and the default allocator. If you pass the address of
a local ccol_memmgmt_procs directly, the compiler can prove that the
test is always true, and GCC may then report -Waddress ("the address of
X will always evaluate as true"), which -Werror turns into an error. To
avoid it, put the address in a ccol_memmgmt_procs * variable and pass
that variable to both the macro and the allocation.
 
The macro expands to two declarations rather than one expression, so it
has to be a statement of its own, the same as every *_construct_scoped
macro of the library.

There is no synchronisation. The pointer is a plain local variable and
follows the ordinary C rules for scope and thread-local storage. As with
every _mp API of the library, the thread safety of the functions in
mmgmt_procs is up to the caller.

#include <stdlib.h>
 
void process(ccol_memmgmt_procs *mp) {
  ccol_scoped_ptr_mp(buf, char, mp);
  buf = mp ? mp->malloc(128) : malloc(128);
  if (!buf) return;
 
  /* buf is used here */
 
}  /* mp frees buf on every return path */

ccol_scoped_ptr(3), ccol_scoped_ptr_release(3), ccollections(7)