home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 3-13.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  1KB  |  53 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. // stddef.h to get size_t
  7. #include <stddef.h>
  8.  
  9. #define HEAP_BASE_ADDRESS 0x001000;
  10.  
  11. struct Head {
  12.    long length;
  13.    struct Head *next;
  14. };
  15.  
  16. static Head pool = { 0, 0 };
  17.  
  18. static Head *h = (Head *)HEAP_BASE_ADDRESS;
  19.  
  20. /* fast dumb first-fit allocator */
  21.  
  22. typedef char *Char_p;
  23.  
  24. // NEXT LINE IS MACHINE AND COMPILER DEPENDENT:
  25. const long WRDSIZE = sizeof(void*);
  26.  
  27. void* operator new(size_t nbytes)
  28. {
  29.     /* First, look in free list */
  30.     if (pool.next) {
  31.         Head *prev = &pool;
  32.         for (Head *cur = &pool; cur; cur = cur->next) {
  33.             if (cur->length >= nbytes) {
  34.                 prev->next = cur->next;
  35.                 return (void*)(Char_p(cur) + sizeof(Head));
  36.             } else prev = cur;
  37.         }
  38.     }
  39.     /* Nothing on free list, get new block from heap */
  40.     h = (Head*)(((int)((Char_p(h)+WRDSIZE-1))/WRDSIZE)*WRDSIZE);
  41.     h->next = 0;
  42.     h->length = nbytes;
  43.     h += nbytes + sizeof(Head);
  44.     return (void*)(Char_p(h) + sizeof(Head));
  45. }
  46.  
  47. void operator delete(void *ptr)
  48. {
  49.     Head *p = (Head *)(Char_p(ptr) - sizeof(Head));
  50.     p->next = pool.next;
  51.     pool.next = p;
  52. }
  53.