Listing 2

/* These enhanced "wrappers" pad the dynamic object
   with a serial number.
   
   The adjptr manipulations are a kludge. I can't do
   the necessary pointer arithmetic on void pointers,
   so I create char pointers, manipulate them and
   then cast back. There must be a better way!
*/

#ifndef HWRAPPER
#ifdef DEBUG
#define HWRAPPER
int count;
int fcount;   /* count free calls separately */
FILE * log;

void my_free(void * tree)
{
       char * adjptr;
       
       adjptr = (char *) tree;
       adjptr -= sizeof(int) ;
       if (log == NULL) log = fopen("log","w");
       fprintf(log,"%p %5.5d free %d\n",adjptr,
                 *((int * ) adjptr),fcount++ );
       free( (void *) adjptr );
}

void * my_alloc(size_t size)
{
       void * temp;
       char * adjptr;
       
       if (log == NULL) log = fopen("log","w");
       temp = (void *) malloc( size + sizeof(int) );
       *( (int * ) temp ) = count;
       fprintf(log,"%p %5.5d anew\n",temp,count++);
       adjptr = (char *) temp;
       adjptr += sizeof(int);
       return (void *) adjptr ;
}

#define malloc(x) my_alloc(x)

#define free(x) my_free(x)

#endif
#endif

/* End of File */