Back to index

radiance  4R0+20100331
bmalloc.c
Go to the documentation of this file.
00001 #ifndef lint
00002 static const char    RCSid[] = "$Id: bmalloc.c,v 2.9 2004/10/23 18:55:52 schorsch Exp $";
00003 #endif
00004 /*
00005  * Bmalloc provides basic memory allocation without overhead (no free lists).
00006  * Use only to take the load off of malloc for all those
00007  * piddling little requests that you never expect to free.
00008  * Bmalloc defers to malloc for big requests.
00009  * Bfree should hand memory to bmalloc, but it usually fails here.
00010  *
00011  *  External symbols declared in standard.h
00012  */
00013 
00014 #include "copyright.h"
00015 
00016 #include <stdlib.h>
00017 
00018 #include "rtmisc.h"
00019 
00020 #ifndef  MBLKSIZ
00021 #define  MBLKSIZ     16376         /* size of memory allocation block */
00022 #endif
00023 #define  WASTEFRAC   12            /* don't waste more than a fraction */
00024 #ifndef  ALIGNT
00025 #define  ALIGNT             double        /* type for alignment */
00026 #endif
00027 #define  BYTES_WORD  sizeof(ALIGNT)
00028 
00029 static char  *bposition = NULL;
00030 static size_t  nremain = 0;
00031 
00032 
00033 void *
00034 bmalloc(             /* allocate a block of n bytes */
00035 register size_t  n
00036 )
00037 {
00038        if (n > nremain && (n > MBLKSIZ || nremain > MBLKSIZ/WASTEFRAC))
00039               return(malloc(n));                 /* too big */
00040 
00041        n = (n+(BYTES_WORD-1))&~(BYTES_WORD-1);          /* word align */
00042 
00043        if (n > nremain && (bposition = malloc(nremain = MBLKSIZ)) == NULL) {
00044               nremain = 0;
00045               return(NULL);
00046        }
00047        bposition += n;
00048        nremain -= n;
00049        return(bposition - n);
00050 }
00051 
00052 
00053 void
00054 bfree(               /* free random memory */
00055 register void *pp,
00056 register size_t      n
00057 )
00058 {
00059        register char *p = pp;
00060        register size_t      bsiz;
00061                                    /* check alignment */
00062        bsiz = BYTES_WORD - ((size_t)p&(BYTES_WORD-1));
00063        if (bsiz < BYTES_WORD) {
00064               p += bsiz;
00065               n -= bsiz;
00066        }
00067        if (p + n == bposition) {   /* just allocated? */
00068               bposition = p;
00069               nremain += n;
00070               return;
00071        }
00072        if (n > nremain) {          /* better than what we've got? */
00073               bposition = p;
00074               nremain = n;
00075               return;
00076        }
00077                             /* just throw it away, then */
00078 }