|
|
1.1 root 1: #include <stdio.h>
2: #include <assert.h>
3: #include "mem.h"
4:
5: #define BLKF 100
6:
7: static struct _mem *mlist;
8:
9: static void
10: zap(cp,size)
11: char *cp;
12: int size;
13: {
14: for(;size>0;size--) {
15: *cp = 0xff;
16: }
17: }
18: void
19: mem_init(mp, size)
20: struct _mem *mp;
21: int size;
22: {
23: int i, s;
24: assert(size>=4);
25: mp->size = s = size;
26: s *= BLKF;
27: for (i=1; i < s; i <<= 1);
28: mp->bsize = i;
29: mp->blkf = mp->bsize/size;
30: mp->cnt = 0;
31: mp->freelist = NULL;
32: mp->totelem = 0;
33: mp->freecnt = 0;
34: mp->next = mlist;
35: mlist = mp;
36: };
37:
38: char *
39: mem_get(mp)
40: struct _mem *mp;
41: {
42: char *cp;
43: if (mp->freelist!=NULL) {
44: cp = mp->freelist;
45: mp->freelist = *(char **) cp;
46: mp->freecnt--;
47: zap(cp,mp->size);
48: return(cp);
49: } else if (mp->cnt==0) {
50: mp->block = (char *)malloc(mp->bsize);
51: mp->cnt = mp->blkf;
52: mp->totelem += mp->blkf;
53: }
54: mp->cnt--;
55: cp = mp->block;
56: mp->block += mp->size;
57: zap(cp,mp->size);
58: return(cp);
59: }
60:
61: mem_free(mp, cp)
62: struct _mem *mp;
63: char *cp;{
64: *(char **)cp = mp->freelist;
65: mp->freelist = cp;
66: mp->freecnt++;
67: }
68:
69: mem_outstanding(mp)
70: struct _mem *mp;
71: {
72: /* returns elements that are outstanding..i.e. asked for
73: * but haven't yet been returned
74: */
75: return(mp->totelem - (mp->cnt+mp->freecnt));
76: }
77:
78: mem_epilogue()
79: {
80: struct _mem *mp;
81: /*
82: * if the following assertion fails then one of the following
83: * has happened:
84: * 1) somebody forgot to free something or
85: * 2) there is leakage.
86: */
87: for(mp=mlist; mp!=NULL; mp = mp->next) {
88: assert(mem_outstanding(mp)==0);
89: }
90: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.