home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1998 May / Pcwk5b98.iso / Borland / Cplus45 / BC45 / OWL1.PAK / SAFEPOOL.CPP < prev    next >
Text File  |  1995-08-29  |  2KB  |  75 lines

  1. // Borland C++ - (C) Copyright 1992 by Borland International
  2.  
  3. #include <stddef.h>
  4. #include <stdlib.h>
  5. #include <safepool.h>
  6.  
  7. typedef void (_FAR *pvf)();
  8.  
  9. pvf _new_handler;
  10.  
  11. int    SafetyPool::Size = DEFAULT_SAFETY_POOL_SIZE;
  12. void _FAR *  SafetyPool::safetyPool = new char[DEFAULT_SAFETY_POOL_SIZE];
  13.  
  14. pvf set_new_handler(pvf p)
  15. {
  16.     pvf t = _new_handler;
  17.     _new_handler = p;
  18.     return t;
  19. }
  20.  
  21. static void _FAR *originalNew(size_t size)
  22. {
  23.     void _FAR * p;
  24.  
  25.     size = size ? size : 1;
  26.     while ( (p = malloc(size)) == NULL && _new_handler != NULL)
  27.         _new_handler();
  28.     return p;
  29. }
  30.  
  31. void _FAR *operator new( size_t size )
  32. {
  33.     void _FAR *allocated = originalNew (size);
  34.     if (allocated == 0)
  35.         if (SafetyPool::IsExhausted())
  36.             return NULL;
  37.         else
  38.         {
  39.             delete SafetyPool::safetyPool;
  40.             SafetyPool::safetyPool = 0;
  41.             allocated = originalNew (size);
  42.             if (allocated == 0)
  43.                 return NULL;
  44.         }
  45.         return allocated;
  46. }
  47.  
  48. void operator delete( void _FAR *ptr )
  49. {
  50.     if (ptr)
  51.     {
  52.         free(ptr);
  53.  
  54.         // try to restore the safety pool if it is exhausted
  55.         if (SafetyPool::IsExhausted())
  56.             SafetyPool::Allocate();
  57.     }
  58. }
  59.  
  60. /* This static member function deletes the existing safetypool and
  61.    reallocates one with the specified size.  It returns TRUE if this
  62.    is successful, otherwise FALSE.  Note that if this function returns
  63.    FALSE, the next call to check on the safety pool will indicate the
  64.    low memory condition. */
  65.  
  66. int SafetyPool::Allocate(size_t size)
  67. {
  68.     delete safetyPool;         // delete existing safetyPool
  69.     
  70.     safetyPool = new char[size]; // reallocate safetyPool
  71.     Size       = size;
  72.  
  73.     return !IsExhausted(); // return success/failure
  74. }
  75.