www.delorie.com/gnu/docs/avl/libavl_83.html   search  
 
Buy GNU books!


GNU libavl 2.0.1

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.14.4 Memory Manager

We want to test our code to make sure that it always releases allocated memory and that it behaves robustly when memory allocations fail. We can do the former by building our own memory manager that keeps tracks of blocks as they are allocated and freed. The memory manager can also disallow allocations according to a policy set by the user, taking care of the latter.

The available policies are:

 
/* Memory tracking policy. */
enum mt_policy 
{ MT_TRACK, /* Track allocation for leak detection. */ MT_NO_TRACK, /* No leak detection. */ MT_FAIL_COUNT, /* Fail allocations after a while. */ MT_FAIL_PERCENT, /* Fail allocations randomly. */ MT_SUBALLOC /* Suballocate from larger blocks. */ };

MT_TRACK and MT_NO_TRACK should be self-explanatory. MT_FAIL_COUNT takes an argument specifying after how many allocations further allocations should always fail. MT_FAIL_PERCENT takes an argument specifying an integer percentage of allocations to randomly fail.

MT_SUBALLOC causes small blocks to be carved out of larger ones allocated with malloc(). This is a good idea for two reasons: malloc() can be slow and malloc() can waste a lot of space dealing with the small blocks that libavl uses for its node. Suballocation cannot be implemented in an entirely portable way because of alignment issues, but the test program here requires the user to specify the alignment needed, and its use is optional anyhow.

The memory manager keeps track of allocated blocks using struct block:

 
/* Memory tracking allocator. */
/* A memory block. */
struct block 
{ struct block *next; /* Next in linked list. */ int idx; /* Allocation order index number. */ size_t size; /* Size in bytes. */ size_t used; /* MT_SUBALLOC: amount used so far. */ void *content; /* Allocated region. */ };
See also @refalso{127 This code is included in @refalso{97

The next member of struct block is used to keep a linked list of all the currently allocated blocks. Searching this list is inefficient, but there are at least two reasons to do it this way, instead of using a more efficient data structure, such as a binary tree. First, this code is for testing binary tree routines--using a binary tree data structure to do it is a strange idea! Second, the ISO C standard says that, with few exceptions, using the relational operators (<, <=, >, >=) to compare pointers that do not point inside the same array produces undefined behavior, but allows use of the equality operators (==, !=) for a larger class of pointers.

We also need a data structure to keep track of settings and a list of blocks. This memory manager uses the technique discussed in Exercise 2.5-3 to provide this structure to the allocator.

 
/* Indexes into arg[] within struct mt_allocator. */
enum mt_arg_index 
{ MT_COUNT = 0, /* MT_FAIL_COUNT: Remaining successful allocations. */ MT_PERCENT = 0, /* MT_FAIL_PERCENT: Failure percentage. */ MT_BLOCK_SIZE = 0, /* MT_SUBALLOC: Size of block to suballocate. */ MT_ALIGN = 1 /* MT_SUBALLOC: Alignment of suballocated blocks. */ }; /* Memory tracking allocator. */ struct mt_allocator
{ struct libavl_allocator allocator; /* Allocator. Must be first member. */ /* Settings. */ enum mt_policy policy; /* Allocation policy. */ int arg[2]; /* Policy arguments. */ int verbosity; /* Message verbosity level. */ /* Current state. */ struct block *head, *tail; /* Head and tail of block list. */ int alloc_idx; /* Number of allocations so far. */ int block_cnt; /* Number of still-allocated blocks. */ };

Function mt_create() creates a new instance of the memory tracker. It takes an allocation policy and policy argument, as well as a number specifying how verbose it should be in reporting information. It uses utility function xmalloc(), a simple wrapper for malloc() that aborts the program on failure. Here it is:

 
static void *mt_allocate (struct libavl_allocator *, size_t);
static void mt_free (struct libavl_allocator *, void *);
/* Initializes the memory manager for use 
   with allocation policy policy and policy arguments arg[],
   at verbosity level verbosity, where 0 is a ``normal'' value. */
struct mt_allocator *
mt_create (enum mt_policy policy, int arg[2], int verbosity)
{ struct mt_allocator *mt = xmalloc (sizeof *mt); mt-&#62;allocator.libavl_malloc = mt_allocate; mt-&#62;allocator.libavl_free = mt_free; mt-&#62;policy = policy; mt-&#62;arg[0] = arg[0]; mt-&#62;arg[1] = arg[1]; mt-&#62;verbosity = verbosity; mt-&#62;head = mt-&#62;tail = NULL; mt-&#62;alloc_idx = 0; mt-&#62;block_cnt = 0; return mt; }

After allocations and deallocations are done, the memory manager must be freed with mt_destroy(), which also reports any memory leaks. Blocks are removed from the block list as they are freed, so any remaining blocks must be leaked memory:

 
/* Frees and destroys memory tracker mt, 
reporting any memory leaks. */ void
mt_destroy (struct mt_allocator *mt)
{ assert (mt != NULL); if (mt-&#62;block_cnt == 0)
{ if (mt-&#62;policy != MT_NO_TRACK && mt-&#62;verbosity >= 1) printf ("Nomemoryleaks.\n"); }
else
{ struct block *iter, *next; if (mt-&#62;policy != MT_SUBALLOC)
printf ("Memoryleaksdetected:\n"); for (iter = mt-&#62;head; iter != NULL; iter = next)
{ if (mt-&#62;policy != MT_SUBALLOC) printf ("block#%d:%lubytes\n", iter-&#62;idx, (unsigned long) iter-&#62;size); next = iter-&#62;next; free (iter-&#62;content); free (iter); } } free (mt); }

For the sake of good encapsulation, mt_allocator() returns the struct libavl_allocator associated with a given memory tracker:

 
/* Returns the struct libavl_allocator associated with mt. */
void *
mt_allocator (struct mt_allocator *mt)
{ return &mt-&#62;allocator; }

The allocator function mt_allocate() is in charge of implementing the selected allocation policy. It delegates most of the work to a pair of helper functions new_block() and reject_request() and makes use of utility function xmalloc(), a simple wrapper for malloc() that aborts the program on failure. The implementation is straightforward:

 
/* Creates a new struct block containing size bytes of content
   and returns a pointer to content. */
static void *
new_block (struct mt_allocator *mt, size_t size)
{ struct block *new; /* Allocate and initialize new struct block. */ new = xmalloc (sizeof *new); new-&#62;next = NULL; new-&#62;idx = mt-&#62;alloc_idx++; new-&#62;size = size; new-&#62;used = 0; new-&#62;content = xmalloc (size); /* Add block to linked list. */ if (mt-&#62;head == NULL) mt-&#62;head = new; else
mt-&#62;tail-&#62;next = new; mt-&#62;tail = new; /* Alert user. */ if (mt-&#62;verbosity >= 3) printf ("block#%d:allocated%lubytes\n", new-&#62;idx, (unsigned long) size); /* Finish up and return. */ mt-&#62;block_cnt++; return new-&#62;content; } /* Prints a message about a rejected allocation if appropriate. */ static void
reject_request (struct mt_allocator *mt, size_t size)
{ if (mt-&#62;verbosity >= 2) printf ("block#%d:rejectedrequestfor%lubytes\n", mt-&#62;alloc_idx++, (unsigned long) size); } /* Allocates and returns a block of size bytes. */ static void *
mt_allocate (struct libavl_allocator *allocator, size_t size)
{ struct mt_allocator *mt = (struct mt_allocator *) allocator; /* Special case. */ if (size == 0) return NULL; switch (mt-&#62;policy)
{ case MT_TRACK:
return new_block (mt, size); case MT_NO_TRACK:
return xmalloc (size); case MT_FAIL_COUNT: if (mt-&#62;arg[MT_COUNT] == 0)
{ reject_request (mt, size); return NULL; } mt-&#62;arg[MT_COUNT]--; return new_block (mt, size); case MT_FAIL_PERCENT: if (rand () / (RAND_MAX / 100 + 1) < mt-&#62;arg[MT_PERCENT])
{ reject_request (mt, size); return NULL; } else
return new_block (mt, size); case MT_SUBALLOC: if (mt-&#62;tail == NULL || mt-&#62;tail-&#62;used + size > (size_t) mt-&#62;arg[MT_BLOCK_SIZE]) new_block (mt, mt-&#62;arg[MT_BLOCK_SIZE]); if (mt-&#62;tail-&#62;used + size <= (size_t) mt-&#62;arg[MT_BLOCK_SIZE])
{ void *p = (char *) mt-&#62;tail-&#62;content + mt-&#62;tail-&#62;used; size = ((size + mt-&#62;arg[MT_ALIGN] - 1) / mt-&#62;arg[MT_ALIGN] * mt-&#62;arg[MT_ALIGN]); mt-&#62;tail-&#62;used += size; if (mt-&#62;verbosity >= 3) printf ("block#%d:suballocated%lubytes\n", mt-&#62;tail-&#62;idx, (unsigned long) size); return p; } else
fail ("blocksize%lutoosmallfor%lu-byteallocation", (unsigned long) mt-&#62;tail-&#62;size, (unsigned long) size); default:
assert (0); } }

The corresponding function mt_free() searches the block list for the specified block, removes it, and frees the associated memory. It reports an error if the block is not in the list:

 
/* Releases block previously returned by mt_allocate(). */
static void 
mt_free (struct libavl_allocator *allocator, void *block)
{ struct mt_allocator *mt = (struct mt_allocator *) allocator; struct block *iter, *prev; /* Special cases. */ if (block == NULL || mt-&#62;policy == MT_NO_TRACK)
{ free (block); return; } if (mt-&#62;policy == MT_SUBALLOC) return; /* Search for block within the list of allocated blocks. */ for (prev = NULL, iter = mt-&#62;head; iter; prev = iter, iter = iter-&#62;next)
{ if (iter-&#62;content == block)
{ /* Block found. Remove it from the list. */ struct block *next = iter-&#62;next; if (prev == NULL) mt-&#62;head = next; else
prev-&#62;next = next; if (next == NULL)
mt-&#62;tail = prev; /* Alert user. */ if (mt-&#62;verbosity >= 4) printf ("block#%d:freed%lubytes\n", iter-&#62;idx, (unsigned long) iter-&#62;size); /* Free block. */ free (iter-&#62;content); free (iter); /* Finish up and return. */ mt-&#62;block_cnt--; return; } } /* Block not in list. */ printf ("attempttofreeunknownblock%p(alreadyfreed?)\n", block); }

See also: [ ISO 1990], sections 6.3.8 and 6.3.9.

Exercises:

1. As its first action, mt_allocate() checks for and special-cases a size of 0. Why? [answer]


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster   donations   bookstore     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003