home *** CD-ROM | disk | FTP | other *** search
- /**
- *** Name ...... : mem.c
- *** Purpose ... : fixed-size memory blocks allocation
- *** Author .... : ...sigh! I lost it!
- *** Note ...... : from "The C User Journal"
- **/
-
- #include <stdio.h>
- #include "mem.h"
-
- static union freelist *
- create_freelist (flh, bytes)
- FlistHead *flh;
- int bytes;
-
- {
- char *sbrk ();
- union freelist *current = (union freelist *) sbrk (bytes);
-
- if ((union freelist *) - 1 == current)
- return 0;
- flh->freelist = current;
- while (((char *) current + flh->size) < ((char *) flh->freelist + bytes))
- {
- current->next = (union freelist *) (¤t->memory + flh->size);
- current = current->next;
- }
- current->next = NULL;
- return current;
- }
-
- void
- MemInit (flh, size, alloc1, alloc2)
- FlistHead *flh;
- int size;
- int alloc1, alloc2;
-
- {
- flh->size = (size > sizeof (union freelist *) ? size : sizeof (union freelist *));
- flh->bytes = flh->size * alloc2;
- if (0 == create_freelist (flh, flh->size * alloc1))
- {
- fprintf (stderr, "MemInit: out of space\n");
- exit (-1);
- }
- }
-
- VOID *
- new (flh)
- FlistHead *flh;
-
- {
- VOID *obj;
-
- if (flh->freelist == NULL && 0 == create_freelist (flh, flh->bytes))
- {
- fprintf (stderr, "new: out of space\n");
- exit (-1);
- }
-
- obj = (VOID *) & flh->freelist->memory;
-
- flh->freelist = flh->freelist->next;
-
- return obj;
- }
-
- void
- delete (flh, link)
- FlistHead *flh;
- VOID *link;
-
- {
- ((union freelist *) link)->next = flh->freelist;
- flh->freelist = (union freelist *) link;
- }
-