C Collections

ccollections · Section 3

ccol_scoped_ptr

ccol_scoped_ptr - declare a raw pointer that is freed automatically at scope exit

C Collections (libccollections, -lccollections)

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

Declares "type *name", sets it to NULL and registers an automatic
cleanup with __attribute__((cleanup(...))). You assign to name as usual,
with a plain malloc() for example, and at the end of the enclosing scope
the value that name holds is freed with the default allocator, which is
a plain free().
 
It is the same as ccol_scoped_ptr_mp(name, type, NULL). Use
ccol_scoped_ptr_mp() when the pointer has to be freed by a custom
library-wide allocator instead of the default one.
 
The containers of this library each have a *_construct_scoped macro of
their own. This one has no container type attached to it, and it is
there for a plain heap block that is not a chmap, a cbmap, a cvec or any
other container.

name  The name of the pointer variable to declare
type  The type that the pointer points to (for example char, struct foo)

Needs GCC or Clang, because it uses __attribute__((cleanup)).
 
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.
 
Only the last value of name is freed. If you give name a new value
inside the scope, you must free the earlier value yourself before the
assignment, or it is lost. Any guard built on the cleanup attribute
behaves this way.
 
To hand the pointer to code outside the enclosing scope, for example as
the return value of a function, call ccol_scoped_ptr_release(); the
pointer is then not freed at the end of the scope.

There is no synchronisation. The pointer is a plain local variable and
follows the ordinary C rules for scope and thread-local storage.

void process(void) {
  ccol_scoped_ptr(buf, char);
  buf = malloc(128);
  if (!buf) return;
 
  /* buf is used here */
 
}  /* buf is freed automatically here, on every return path */

ccol_scoped_ptr_mp(3), ccol_scoped_ptr_release(3)