4 * Memory routines with out-of-memory checking.
6 * Copyright 1996-2003 Glyph & Cog, LLC
18 typedef struct _GMemHdr {
21 struct _GMemHdr *next;
24 #define gMemHdrSize ((sizeof(GMemHdr) + 7) & ~7)
25 #define gMemTrlSize (sizeof(long))
28 #define gMemDeadVal 0xdeadbeefdeadbeefUL
30 #define gMemDeadVal 0xdeadbeefUL
33 /* round data size so trailer will be aligned */
34 #define gMemDataSize(size) \
35 ((((size) + gMemTrlSize - 1) / gMemTrlSize) * gMemTrlSize)
38 #define gMemListShift 4
39 #define gMemListMask (gMemNLists - 1)
40 static GMemHdr *gMemList[gMemNLists] = {
41 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
42 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
43 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
44 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
45 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
46 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
47 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
48 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
51 static int gMemIndex = 0;
52 static int gMemAlloc = 0;
54 #endif /* DEBUG_MEM */
56 void *gmalloc(int size) {
63 unsigned long *trl, *p;
67 size1 = gMemDataSize(size);
68 if (!(mem = (char *)malloc(size1 + gMemHdrSize + gMemTrlSize))) {
69 fprintf(stderr, "Out of memory\n");
73 data = (void *)(mem + gMemHdrSize);
74 trl = (unsigned long *)(mem + gMemHdrSize + size1);
76 hdr->index = gMemIndex++;
77 lst = ((int)hdr >> gMemListShift) & gMemListMask;
78 hdr->next = gMemList[lst];
81 for (p = (unsigned long *)data; p <= trl; ++p)
89 if (!(p = malloc(size))) {
90 fprintf(stderr, "Out of memory\n");
97 void *grealloc(void *p, int size) {
109 hdr = (GMemHdr *)((char *)p - gMemHdrSize);
112 memcpy(q, p, size < oldSize ? size : oldSize);
127 q = realloc(p, size);
131 fprintf(stderr, "Out of memory\n");
138 void gfree(void *p) {
142 GMemHdr *prevHdr, *q;
144 unsigned long *trl, *clr;
147 hdr = (GMemHdr *)((char *)p - gMemHdrSize);
148 lst = ((int)hdr >> gMemListShift) & gMemListMask;
149 for (prevHdr = NULL, q = gMemList[lst]; q; prevHdr = q, q = q->next) {
155 prevHdr->next = hdr->next;
157 gMemList[lst] = hdr->next;
159 size = gMemDataSize(hdr->size);
160 trl = (unsigned long *)((char *)hdr + gMemHdrSize + size);
161 if (*trl != gMemDeadVal) {
162 fprintf(stderr, "Overwrite past end of block %d at address %p\n",
165 for (clr = (unsigned long *)hdr; clr <= trl; ++clr)
169 fprintf(stderr, "Attempted to free bad address %p\n", p);
179 void gMemReport(FILE *f) {
183 fprintf(f, "%d memory allocations in all\n", gMemIndex);
185 fprintf(f, "%d memory blocks left allocated:\n", gMemAlloc);
186 fprintf(f, " index size\n");
187 fprintf(f, "-------- --------\n");
188 for (lst = 0; lst < gMemNLists; ++lst) {
189 for (p = gMemList[lst]; p; p = p->next)
190 fprintf(f, "%8d %8d\n", p->index, p->size);
193 fprintf(f, "No memory blocks left allocated\n");
198 char *copyString(char *s) {
201 s1 = (char *)gmalloc(strlen(s) + 1);