/* These enhanced "wrappers" pad the dynamic object
   with a serial number and a trailing fence post.
*/   

#ifndef HWRAPPER
#ifdef DEBUG
#define HWRAPPER

#define SIGWORD 0xAA55

int count;
int fcount;   /* count free calls separately */
FILE * log;

void my_free(void * tree)
{
        char * adjptr;
        char * fenceptr;
        
        fenceptr = adjptr = (char *) tree;
	adjptr -= sizeof(size_t);  /* step back to size */
	fenceptr += * ((size_t *) adjptr);  /* add size */
	adjptr -= sizeof(int);
	if (log == NULL) log = fopen("log","w");
	fprintf(log,"%p %5.5d free %d\n",adjptr, * ((int * ) adjptr),fcount);
	if (*( (unsigned int *) fenceptr) != SIGWORD)
	   fprintf(log,"%p %5.5d damaged object %d\n",adjptr,
	        * ((int *) adjptr), fcount);
	fcount += 1;
        free( (void *) adjptr );
}

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

        adjptr = (char *) temp;
        *( (int * ) adjptr ) = count++;
        adjptr += sizeof(int);
        *( (size_t *) adjptr) = size;
        temp = (void *) (adjptr += sizeof(size_t));
        adjptr += size;
        *( (unsigned int *) adjptr) = SIGWORD;
	return temp ;
}

#define malloc(x) my_alloc(x)

#define free(x)  my_free(x)

#endif
#endif

