home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume4 / rolodex / part3 / toolsdir / mem.c < prev    next >
Encoding:
C/C++ Source or Header  |  1986-11-30  |  2.1 KB  |  89 lines

  1. /**************************************************************************/
  2. /**************************************************************************/
  3.  
  4.  
  5.                   /***** Block Memory Allocator *****/
  6.  
  7.  
  8. /**************************************************************************/
  9. /**************************************************************************/
  10.  
  11. /* Author: JP Massar */
  12.  
  13. #include <stdio.h>
  14.  
  15. #include "sys5.h"
  16.  
  17. #ifdef BSD42
  18. #include <strings.h>
  19. #endif
  20.  
  21. #define NO_MORE_MEMORY -1
  22.  
  23. static int bytes_left;                  /* space left in current block */
  24. static char *ptr_next_byte;             /* next free byte */
  25. static char *ptr_space;                 /* current block */
  26. static int chunk_size;                  /* size of block last allocated */
  27.  
  28. extern char *malloc();
  29.  
  30.  
  31. int allocate_memory_chunk (space) int space;
  32.  
  33. /* malloc up a new block of memory.  Set our static variables */
  34. /* returns NO_MORE_MEMORY if can't allocate block. */
  35.  
  36.   if (0 == (ptr_space = malloc(space))) {
  37.         fprintf(stderr,"fatal error, no more memory\n");
  38.         return(NO_MORE_MEMORY);
  39.   }
  40.   ptr_next_byte = ptr_space;
  41.   bytes_left = space;
  42.   chunk_size = space;
  43.   return(0);
  44. }
  45.  
  46.  
  47. char * get_memory_chunk (size) int size;
  48.  
  49. /* allocate a small segment out of our large block of memory.  If we */
  50. /* run out allocate another block.  Adjust our static variables. */
  51. /* returns 0 if no more memory. */
  52.  
  53. { char *rval;
  54.         
  55.   if (size > chunk_size) {
  56.         fprintf(stderr,"attempt to allocate too large a chunk\n");
  57.         return(0);
  58.   }
  59.         
  60.   if (size > bytes_left) {
  61.         if (NO_MORE_MEMORY == allocate_memory_chunk(chunk_size)) {
  62.                 return(0);
  63.         }
  64.         return(get_memory_chunk(size));
  65.   }
  66.  
  67.   rval = ptr_next_byte;
  68.   ptr_next_byte += size;
  69.   bytes_left -= size;
  70.   return(rval);
  71.   
  72. }
  73.  
  74.  
  75. char * store_string (str,len) char *str; int len;
  76.  
  77. /* put copy of a string into storage in a memory block.  Return a pointer to */
  78. /* the copied string.  Returns 0 if out of memory. */
  79.  
  80. { char *ptr_space;
  81.  
  82.   if (0 == (ptr_space = get_memory_chunk(len+1))) {
  83.         return(0);
  84.   }
  85.   strcpy(ptr_space,str);
  86.   return(ptr_space);
  87. }
  88.