1 |
greg |
1.1 |
#ifndef lint |
2 |
schorsch |
2.9 |
static const char RCSid[] = "$Id: bmalloc.c,v 2.8 2004/10/03 20:48:53 schorsch Exp $"; |
3 |
greg |
1.1 |
#endif |
4 |
|
|
/* |
5 |
greg |
1.3 |
* Bmalloc provides basic memory allocation without overhead (no free lists). |
6 |
|
|
* Use only to take the load off of malloc for all those |
7 |
|
|
* piddling little requests that you never expect to free. |
8 |
|
|
* Bmalloc defers to malloc for big requests. |
9 |
|
|
* Bfree should hand memory to bmalloc, but it usually fails here. |
10 |
greg |
2.3 |
* |
11 |
|
|
* External symbols declared in standard.h |
12 |
greg |
1.1 |
*/ |
13 |
|
|
|
14 |
greg |
2.4 |
#include "copyright.h" |
15 |
greg |
2.3 |
|
16 |
|
|
#include <stdlib.h> |
17 |
schorsch |
2.5 |
|
18 |
|
|
#include "rtmisc.h" |
19 |
greg |
1.2 |
|
20 |
greg |
1.1 |
#ifndef MBLKSIZ |
21 |
|
|
#define MBLKSIZ 16376 /* size of memory allocation block */ |
22 |
|
|
#endif |
23 |
greg |
1.3 |
#define WASTEFRAC 12 /* don't waste more than a fraction */ |
24 |
greg |
2.3 |
#ifndef ALIGNT |
25 |
|
|
#define ALIGNT double /* type for alignment */ |
26 |
greg |
1.1 |
#endif |
27 |
greg |
2.3 |
#define BYTES_WORD sizeof(ALIGNT) |
28 |
greg |
1.1 |
|
29 |
schorsch |
2.8 |
static char *bposition = NULL; |
30 |
schorsch |
2.7 |
static size_t nremain = 0; |
31 |
greg |
1.3 |
|
32 |
|
|
|
33 |
schorsch |
2.7 |
void * |
34 |
schorsch |
2.6 |
bmalloc( /* allocate a block of n bytes */ |
35 |
schorsch |
2.7 |
register size_t n |
36 |
schorsch |
2.6 |
) |
37 |
greg |
1.1 |
{ |
38 |
greg |
1.3 |
if (n > nremain && (n > MBLKSIZ || nremain > MBLKSIZ/WASTEFRAC)) |
39 |
greg |
1.2 |
return(malloc(n)); /* too big */ |
40 |
greg |
1.1 |
|
41 |
|
|
n = (n+(BYTES_WORD-1))&~(BYTES_WORD-1); /* word align */ |
42 |
|
|
|
43 |
schorsch |
2.7 |
if (n > nremain && (bposition = malloc(nremain = MBLKSIZ)) == NULL) { |
44 |
greg |
2.2 |
nremain = 0; |
45 |
|
|
return(NULL); |
46 |
greg |
1.1 |
} |
47 |
greg |
1.3 |
bposition += n; |
48 |
|
|
nremain -= n; |
49 |
|
|
return(bposition - n); |
50 |
greg |
1.1 |
} |
51 |
|
|
|
52 |
|
|
|
53 |
greg |
2.3 |
void |
54 |
schorsch |
2.6 |
bfree( /* free random memory */ |
55 |
schorsch |
2.9 |
register void *pp, |
56 |
schorsch |
2.7 |
register size_t n |
57 |
schorsch |
2.6 |
) |
58 |
greg |
1.1 |
{ |
59 |
schorsch |
2.9 |
register char *p = pp; |
60 |
schorsch |
2.7 |
register size_t bsiz; |
61 |
greg |
1.3 |
/* check alignment */ |
62 |
schorsch |
2.7 |
bsiz = BYTES_WORD - ((size_t)p&(BYTES_WORD-1)); |
63 |
greg |
1.3 |
if (bsiz < BYTES_WORD) { |
64 |
|
|
p += bsiz; |
65 |
|
|
n -= bsiz; |
66 |
|
|
} |
67 |
|
|
if (p + n == bposition) { /* just allocated? */ |
68 |
|
|
bposition = p; |
69 |
|
|
nremain += n; |
70 |
|
|
return; |
71 |
|
|
} |
72 |
|
|
if (n > nremain) { /* better than what we've got? */ |
73 |
|
|
bposition = p; |
74 |
|
|
nremain = n; |
75 |
|
|
return; |
76 |
|
|
} |
77 |
|
|
/* just throw it away, then */ |
78 |
greg |
1.1 |
} |