home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume23 / tua / part01 / mem.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-09-23  |  1.5 KB  |  77 lines

  1. /**
  2. *** Name ...... :    mem.c
  3. *** Purpose ... :    fixed-size memory blocks allocation
  4. *** Author ....    :    ...sigh! I lost it!
  5. *** Note ...... :    from "The C User Journal"
  6. **/
  7.  
  8. #include    <stdio.h>
  9. #include    "mem.h"
  10.  
  11. static union freelist *
  12. create_freelist (flh, bytes)
  13.      FlistHead *flh;
  14.      int bytes;
  15.  
  16. {
  17.   char *sbrk ();
  18.   union freelist *current = (union freelist *) sbrk (bytes);
  19.  
  20.   if ((union freelist *) - 1 == current)
  21.     return 0;
  22.   flh->freelist = current;
  23.   while (((char *) current + flh->size) < ((char *) flh->freelist + bytes))
  24.     {
  25.       current->next = (union freelist *) (¤t->memory + flh->size);
  26.       current = current->next;
  27.     }
  28.   current->next = NULL;
  29.   return current;
  30. }
  31.  
  32. void 
  33. MemInit (flh, size, alloc1, alloc2)
  34.      FlistHead *flh;
  35.      int size;
  36.      int alloc1, alloc2;
  37.  
  38. {
  39.   flh->size = (size > sizeof (union freelist *) ? size : sizeof (union freelist *));
  40.   flh->bytes = flh->size * alloc2;
  41.   if (0 == create_freelist (flh, flh->size * alloc1))
  42.     {
  43.       fprintf (stderr, "MemInit: out of space\n");
  44.       exit (-1);
  45.     }
  46. }
  47.  
  48. VOID *
  49. new (flh)
  50.      FlistHead *flh;
  51.  
  52. {
  53.   VOID *obj;
  54.  
  55.   if (flh->freelist == NULL && 0 == create_freelist (flh, flh->bytes))
  56.     {
  57.       fprintf (stderr, "new: out of space\n");
  58.       exit (-1);
  59.     }
  60.  
  61.   obj = (VOID *) & flh->freelist->memory;
  62.  
  63.   flh->freelist = flh->freelist->next;
  64.  
  65.   return obj;
  66. }
  67.  
  68. void 
  69. delete (flh, link)
  70.      FlistHead *flh;
  71.      VOID *link;
  72.  
  73. {
  74.   ((union freelist *) link)->next = flh->freelist;
  75.   flh->freelist = (union freelist *) link;
  76. }
  77.