Listing 7 Facade malloc Routines

#include <stdio.h>

extern  char    *malloc();
extern  void    free();

#define PTAB_SIZE       1000

static  struct  {
       int     size;           /* allocated sized */
       char    *ptr;           /* allocated pointer */
}       p_tab[PTAB_SIZE];       /* table of allocated entries */
static  int     cnt = 0;        /* maximum entry number */
static  int     amount = 0;     /* number of bytes allocated */

#ifdef  ANSI_C
char    *loc_malloc(int size, char *fn, int ln)
#else
char    *loc_malloc(size, fn, ln)
int     size;
char    *fn;
int     ln;
#endif
/*
 *      malloc knock off
 *      size - the number of bytes to allocate
 *      fn - the file name of where malloc occured
 *      ln - the line number
 */
{
char    *ptr;

       ptr = malloc(size);
       /*printf("mallocing %d bytes at 0x%lx, %s:%d\n",size,ptr,fn,ln);*/
       if (cnt != -1) {
              int     i;
              int     n;

              n = -1;
              for (i = 0; i < cnt; i++) {
                     if (p_tab[i].ptr == ptr) {
                            printf("!!!!!! ptr was previously allocated\n");
                            printf("FILE: \"%s\" LINE: %d\n",fn,ln);
                     } else if (p_tab[i].ptr == NULL) {
                            n = i;
                     }
              }
              if (n == -1) n = cnt++;
              p_tab[n].ptr = ptr;
              p_tab[n].size = size;
              amount += size;
              if (cnt >= PTAB_SIZE) {
                     cnt = -1;
                     printf("overflowing the malloc table\n");
              }
       }
       return(ptr);
}

#ifdef  ANSI_C
void    loc_free(char *ptr, char *fn, int ln)
#else
void    loc_free(ptr, fn, ln)
char    *ptr;
char    *fn;
int     ln;
#endif
/*
 *      free knock off
 *      ptr - the address to free
 *      fn - the file name of where malloc occured
 *      ln- the line number
 */
 
{
       /*printf("free 0x%lx, %s:%d\n",ptr,fn,ln);*/
       if (cnt != -1) {
              int     i;

              for (i = 0; i < cnt; i++) {
                     if (p_tab[i].ptr == ptr) break;
              }
              if (i >= cnt) {
                     printf("!!!!!! pointer not found in malloc table\n");
                     printf("FILE: \"%s\" LINE: %d\n",fn,ln);
              } else {
                     p_tab[i].ptr = NULL;
                     amount -= p_tab[i].size;
              }
              while((cnt > 0) && (p_tab[cnt-1].ptr == NULL)) cnt-;
       }
       free(ptr);
}

void    print_heap_size()
/*
 *      print out the amount of heap currently being used
 */
{
char    buf[80];

       if (cnt == -1) {
              printf("Too many heap entries; lost track of size\n");
       } else {
              printf("Heap size = %d bytes\n", amount);
       }
}
/* End of File */