memb.c

Go to the documentation of this file.
00001 
00046 #include <string.h>
00047 
00048 #include "memb.h"
00049 
00050 /*---------------------------------------------------------------------------*/
00051 void
00052 memb_init(struct memb_blocks *m)
00053 {
00054   memset(m->count, 0, m->num);
00055   memset(m->mem, 0, m->size * m->num);
00056 }
00057 /*---------------------------------------------------------------------------*/
00058 void *
00059 memb_alloc(struct memb_blocks *m)
00060 {
00061   int i;
00062 
00063   for(i = 0; i < m->num; ++i) {
00064     if(m->count[i] == 0) {
00065       /* If this block was unused, we increase the reference count to
00066          indicate that it now is used and return a pointer to the
00067          memory block. */
00068       ++(m->count[i]);
00069       return (void *)((char *)m->mem + (i * m->size));
00070     }
00071   }
00072 
00073   /* No free block was found, so we return NULL to indicate failure to
00074      allocate block. */
00075   return NULL;
00076 }
00077 /*---------------------------------------------------------------------------*/
00078 char
00079 memb_free(struct memb_blocks *m, void *ptr)
00080 {
00081   int i;
00082   char *ptr2;
00083 
00084   /* Walk through the list of blocks and try to find the block to
00085      which the pointer "ptr" points to. */
00086   ptr2 = (char *)m->mem;
00087   for(i = 0; i < m->num; ++i) {
00088 
00089     if(ptr2 == (char *)ptr) {
00090       /* We've found to block to which "ptr" points so we decrease the
00091          reference count and return the new value of it. */
00092       if(m->count[i] > 0) {
00093         /* Make sure that we don't deallocate free memory. */
00094         --(m->count[i]);
00095       }
00096       return m->count[i];
00097     }
00098     ptr2 += m->size;
00099   }
00100   return -1;
00101 }
00102 /*---------------------------------------------------------------------------*/
00103