SDDS ToolKit Programs and Libraries for C and Python
Loading...
Searching...
No Matches
recycle.c
Go to the documentation of this file.
1/**
2 * @file recycle.c
3 * @brief Memory recycling routines for frequently allocated structures.
4 *
5 * Provides functions that manage pools of reusable memory blocks to
6 * reduce malloc overhead and memory fragmentation. Written by Bob
7 * Jenkins (September 1996) and released to the public domain with no
8 * warranty.
9 */
10
11#ifndef STANDARD
12# include "standard.h"
13#endif
14#ifndef RECYCLE
15# include "recycle.h"
16#endif
17
18reroot *remkroot(size)
19 size_t size;
20{
21 reroot *r = (reroot *)remalloc(sizeof(reroot), "recycle.c, root");
22 r->list = (recycle *)0;
23 r->trash = (recycle *)0;
24 r->size = mdbalign(size);
25 r->logsize = RESTART;
26 r->numleft = 0;
27 return r;
28}
29
30void refree(r) struct reroot *r;
31{
32 recycle *temp;
33 if ((temp = r->list) != NULL)
34 while (r->list) {
35 temp = r->list->next;
36 free((char *)r->list);
37 r->list = temp;
38 }
39 free((char *)r);
40 return;
41}
42
43/* to be called from the macro renew only */
44char *renewx(r) struct reroot *r;
45{
46 recycle *temp;
47 if (r->trash) { /* pull a node off the trash heap */
48 temp = r->trash;
49 r->trash = temp->next;
50 (void)memset((void *)temp, 0, r->size);
51 } else { /* allocate a new block of nodes */
52 r->numleft = r->size * ((size_t)1 << r->logsize);
53 if (r->numleft < REMAX)
54 ++r->logsize;
55 temp = (recycle *)remalloc(sizeof(recycle) + r->numleft, "recycle.c, data");
56 temp->next = r->list;
57 r->list = temp;
58 r->numleft -= r->size;
59 temp = (recycle *)((char *)(r->list + 1) + r->numleft);
60 }
61 return (char *)temp;
62}
63
64char *remalloc(len, purpose)
65 size_t len;
66char *purpose;
67{
68 char *x = (char *)malloc(len);
69 if (!x) {
70 fprintf(stderr, "malloc of %d failed for %s\n", (int)len, purpose);
71 exit(1);
72 }
73 return x;
74}