1 |
greg |
1.1 |
#ifndef lint |
2 |
schorsch |
2.5 |
static const char RCSid[] = "$Id: bmalloc.c,v 2.4 2003/02/25 02:47:21 greg 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 |
greg |
1.3 |
static char *bposition = NULL; |
30 |
greg |
2.3 |
static unsigned int nremain = 0; |
31 |
greg |
1.3 |
|
32 |
|
|
|
33 |
greg |
1.1 |
char * |
34 |
greg |
2.2 |
bmalloc(n) /* allocate a block of n bytes */ |
35 |
greg |
2.3 |
register unsigned int n; |
36 |
greg |
1.1 |
{ |
37 |
greg |
1.3 |
if (n > nremain && (n > MBLKSIZ || nremain > MBLKSIZ/WASTEFRAC)) |
38 |
greg |
1.2 |
return(malloc(n)); /* too big */ |
39 |
greg |
1.1 |
|
40 |
|
|
n = (n+(BYTES_WORD-1))&~(BYTES_WORD-1); /* word align */ |
41 |
|
|
|
42 |
greg |
2.3 |
if (n > nremain && (bposition = (char *)malloc(nremain = MBLKSIZ)) == NULL) { |
43 |
greg |
2.2 |
nremain = 0; |
44 |
|
|
return(NULL); |
45 |
greg |
1.1 |
} |
46 |
greg |
1.3 |
bposition += n; |
47 |
|
|
nremain -= n; |
48 |
|
|
return(bposition - n); |
49 |
greg |
1.1 |
} |
50 |
|
|
|
51 |
|
|
|
52 |
greg |
2.3 |
void |
53 |
greg |
1.1 |
bfree(p, n) /* free random memory */ |
54 |
greg |
1.3 |
register char *p; |
55 |
greg |
2.3 |
register unsigned int n; |
56 |
greg |
1.1 |
{ |
57 |
greg |
2.3 |
register unsigned int bsiz; |
58 |
greg |
1.3 |
/* check alignment */ |
59 |
greg |
2.3 |
bsiz = BYTES_WORD - ((unsigned int)p&(BYTES_WORD-1)); |
60 |
greg |
1.3 |
if (bsiz < BYTES_WORD) { |
61 |
|
|
p += bsiz; |
62 |
|
|
n -= bsiz; |
63 |
|
|
} |
64 |
|
|
if (p + n == bposition) { /* just allocated? */ |
65 |
|
|
bposition = p; |
66 |
|
|
nremain += n; |
67 |
|
|
return; |
68 |
|
|
} |
69 |
|
|
if (n > nremain) { /* better than what we've got? */ |
70 |
|
|
bposition = p; |
71 |
|
|
nremain = n; |
72 |
|
|
return; |
73 |
|
|
} |
74 |
|
|
/* just throw it away, then */ |
75 |
greg |
1.1 |
} |