Coding Guidelines/Memory Allocation

From wiki.zmanda.com
Revision as of 18:40, 30 May 2007 by Dustin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Allocating Memory

Allocate memory with alloc, which is a wrapper around malloc to detect and fail on out-of-memory errors. As glib is incorporated into the codebase, using g_malloc() is OK, too.

The function newalloc is also available -- it is a macro which frees its first argument, if it is not NULL, before allocating. It is used much like the new* string functions:

{
  void *databanks = NULL;
  len = 17;
  /* ... */
  databanks = newalloc(databanks, len);
  /* ... */
  len += 34;
  databanks = newalloc(databanks, len);
  /* ... */
  amfree(databanks);
}

Deallocating Memory

Where possible, use amfree(x), which is a macro that also sets x to NULL. When x is not an lvalue, amfree won't work, and you can fall back to free. g_free is also OK, although it does not set its argument to NULL.