C Collections

ccollections · Section 3

ccol_scoped_ptr_release

ccol_scoped_ptr_release - release the ownership of a scoped pointer so that it is not freed automatically

C Collections (libccollections, -lccollections)

#include <ccollections/common.h>
 
released = ccol_scoped_ptr_release(name);

Returns the current value of name and sets name to NULL, so the cleanup
that ccol_scoped_ptr() or ccol_scoped_ptr_mp() registered for it does
nothing at the end of the scope. You use it to hand the pointer to code
outside the enclosing scope, for example as a function's return value,
and the pointer is then not freed in that scope.
 
Whoever receives the released value has to free it, and must free it
with the allocator that allocated it.

name  A pointer declared earlier with ccol_scoped_ptr() or
      ccol_scoped_ptr_mp()

The value name had just before the release, or NULL if name was never
given a value.

Needs GCC or Clang, as ccol_scoped_ptr() and ccol_scoped_ptr_mp() do.
 
Calling it on a scoped pointer that was never given a value is safe. It
returns NULL and leaves name at NULL.
 
Calling it more than once on the same name is also safe. After the first
call name is NULL, so every later call just returns NULL again.

#include <stdlib.h>
 
char *build(ccol_memmgmt_procs *mp) {
  ccol_scoped_ptr_mp(buf, char, mp);
  buf = mp ? mp->malloc(128) : malloc(128);
  if (!buf) return NULL;
 
  /* ... populate buf ... */
 
  /* after the return, the caller owns buf. The caller frees it with
     mp->free, or with free() when mp is NULL */
  return ccol_scoped_ptr_release(buf);
}

ccol_scoped_ptr(3), ccol_scoped_ptr_mp(3)