clearing entire memory

Dave Jones djones at megatest.UUCP
Fri Dec 1 12:16:46 AEST 1989


>From article <13367 at s.ms.uky.edu>, by kminor at ms.uky.edu (Kevin R. Minor):

> Hello.
> 

Hello.

> ...
> Here's my question.  Is there a way to free up the entire memory
> without having to deallocate each node?

Here's my answer. Sort of.

Define a class of objects, called "heaps" or whatever, that allocate
packets by dividing up much larger blocks of memory. Dedicate a heap to
each large composite structure which you may want to zap all at once.

When it comes time to recycle the memory, you give it back to malloc()
in big chunks rather than little ones. I use a couple of packages like that
extensively. One allocates packets of a fixed size out of a free-list.
The other allocates arbitrary sized packets, which must be returned in
the reverse order, by means of _mark_ and _pop_ procedures. In both
cases, the _allocate_ and _free_ procedures are implemented as macros, and
are much, much faster than the vendor supplied malloc() and free() which
they call only intermittently. Here's the header-file for the fixed size
heap package, to give you the flavor of the thing.


typedef union Heap_unit 
{
  /* The "next" variant is used to link free packets,
   * and to link blocks of packets:
   */
  union Heap_unit* next;

  /* The rest are only dummies, to give the structure the most
   * general alignment characteristic, for better portability.
   */
  float Xflt; double Xdbl;
  char Xchar; short Xshort; long Xlong;
  char *Xcharp; void *Xvoidp; void (*Xfuncp)();
  
} Heap_Unit;

typedef struct heap  /* heap of packets of a fixed size */
{
  int packet_size;      /* ... in units of sizeof(Heap_unit) */
  int num_elements;     /* number of packets to allocate in next block */
  Heap_Unit* cache;     /* linked list of all blocks of packets */
  Heap_Unit* next_free; /* linked free store of packets */
  Heap_Unit* tmp;       /* temporary, used in alloc and free macros */
}Heap; 

extern Ptr Heap_underflow();


/* Public macros */

#define Heap_alloc(obj) \
  ((obj)->next_free == 0 ? \
      Heap_underflow(obj): \
      (Ptr) ( (obj)->tmp = (obj)->next_free, \
	      (obj)->next_free = (obj)->next_free->next, \
	      (obj)->tmp \
	    )   \
   )

#define Heap_free(obj,packet) \
 ((void)( (obj)->tmp = (obj)->next_free,  \
          (obj)->next_free = (Heap_Unit*)packet, \
          ((Heap_Unit*)packet)->next = (obj)->tmp \
        ) \
 )

/* Public routines */

extern Heap* Heap_new();
extern Heap* Heap_init();
extern Heap* Heap_init_sized();

extern Heap* Heap_clean();
extern void  Heap_dispose();



More information about the Comp.lang.c mailing list