SDDSlib
Loading...
Searching...
No Matches
recycle.c
1/*
2 --------------------------------------------------------------------
3 By Bob Jenkins, September 1996. recycle.c
4 You may use this code in any way you wish, and it is free. No warranty.
5
6 This manages memory for commonly-allocated structures.
7 It allocates RESTART to REMAX items at a time.
8 Timings have shown that, if malloc is used for every new structure,
9 malloc will consume about 90% of the time in a program. This
10 module cuts down the number of mallocs by an order of magnitude.
11 This also decreases memory fragmentation, and freeing structures
12 only requires freeing the root.
13 --------------------------------------------------------------------
14*/
15
16#ifndef STANDARD
17# include "standard.h"
18#endif
19#ifndef RECYCLE
20# include "recycle.h"
21#endif
22
23reroot *remkroot(size)
24 size_t size;
25{
26 reroot *r = (reroot *)remalloc(sizeof(reroot), "recycle.c, root");
27 r->list = (recycle *)0;
28 r->trash = (recycle *)0;
29 r->size = mdbalign(size);
30 r->logsize = RESTART;
31 r->numleft = 0;
32 return r;
33}
34
35void refree(r) struct reroot *r;
36{
37 recycle *temp;
38 if ((temp = r->list) != NULL)
39 while (r->list) {
40 temp = r->list->next;
41 free((char *)r->list);
42 r->list = temp;
43 }
44 free((char *)r);
45 return;
46}
47
48/* to be called from the macro renew only */
49char *renewx(r) struct reroot *r;
50{
51 recycle *temp;
52 if (r->trash) { /* pull a node off the trash heap */
53 temp = r->trash;
54 r->trash = temp->next;
55 (void)memset((void *)temp, 0, r->size);
56 } else { /* allocate a new block of nodes */
57 r->numleft = r->size * ((ub4)1 << r->logsize);
58 if (r->numleft < REMAX)
59 ++r->logsize;
60 temp = (recycle *)remalloc(sizeof(recycle) + r->numleft, "recycle.c, data");
61 temp->next = r->list;
62 r->list = temp;
63 r->numleft -= r->size;
64 temp = (recycle *)((char *)(r->list + 1) + r->numleft);
65 }
66 return (char *)temp;
67}
68
69char *remalloc(len, purpose)
70 size_t len;
71char *purpose;
72{
73 char *x = (char *)malloc(len);
74 if (!x) {
75 fprintf(stderr, "malloc of %d failed for %s\n", (int)len, purpose);
76 exit(1);
77 }
78 return x;
79}