Coding Guidelines/Memory Allocation

From wiki.zmanda.com
Jump to navigation Jump to search

General Approach

The general approach to memory allocation and deallocation in Amanda is that code which allocates memory is responsible for deallocating it. Modules should be explicit about their memory-handling behavior in the header or source files: must the caller free the return value of get_foo()?

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.