/*************************************************************************** * Headers ***************************************************************************/ #include #include #include "zmemory.h" /*************************************************************************** * Defines ***************************************************************************/ #define ZMEMORY_MALLOC "malloc" #define ZMEMORY_CALLOC "calloc" #define ZMEMORY_REALLOC "realloc" #define ZMEMORY_FREE "free" #define ZMEMORY_REFREE "refree" /*************************************************************************** * Our output file name (set via: zmemorySetFileName) ***************************************************************************/ static char *zmemoryFileName = NULL; /*************************************************************************** * Local Functions ***************************************************************************/ static void zmemoryProcess( void *address, const char *which, const char *file, int line ) { static const char *formatString = "%p %-8s %s %d\n"; int toStdout = 1; if(zmemoryFileName) { /* -- We don't care to hear about the sins of fopen -- */ #ifdef _WIN32 # pragma warning (disable : 4996) #endif FILE *outFile = fopen(zmemoryFileName, "a"); if(outFile) { fprintf(outFile, formatString, address, which, file, line); fclose(outFile); toStdout = 0; } } if(toStdout) printf(formatString, address, which, file, line); } /*************************************************************************** * Externally Visible Functions ***************************************************************************/ void zmemorySetFileName(const char *fileName) { zmemoryFileName = (char *)fileName; } void *zmemoryMalloc(int theSize, const char *file, int line) { void *ptr = malloc(theSize); zmemoryProcess(ptr, ZMEMORY_MALLOC, file, line); return(ptr); } void *zmemoryCalloc( size_t theNumber, size_t theSize, const char *file, int line ) { void *ptr = calloc(theNumber, theSize); zmemoryProcess(ptr, ZMEMORY_CALLOC, file, line); return(ptr); } void * zmemoryRealloc( void *thePointer, size_t theSize, const char *file, int line ) { void *ptr = realloc(thePointer, theSize); /* -- No need for action unless the pointer has moved -- */ if(ptr != thePointer) { /* -- If 'thePointer' is non-null, realloc will have freed that memory so report that information -- */ if(thePointer) zmemoryProcess(thePointer, ZMEMORY_REFREE, file, line); zmemoryProcess(ptr, ZMEMORY_REALLOC, file, line); } return(ptr); } void zmemoryFree(void *thePointer, const char *file, int line) { zmemoryProcess(thePointer, ZMEMORY_FREE, file, line); free(thePointer); }