1 #ifdef _DEBUG 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 #define _BUF_SIZE 128 8 9 static const char* g_FileName = "HeapLog.txt"; 10 static const char* g_AllocateFail = "分配失败 --- 当前情况(分配:%d, 释放:%d)x0a"; 11 static const char* g_AllocateOK = "分配成功(地址:%p, 大小:%d) --- 当前情况(分配:%d, 释放:%d)x0a"; 12 static const char* g_FreeOK = "释放成功(地址:%p) --- 当前情况(分配:%d, 释放:%d)x0a"; 13 static int g_AllocateNum = 0; 14 static int g_FreeNum = 0; 15 static char g_Buf[_BUF_SIZE]; 16 17 void* operator new(size_t s) 18 { 19 void* p = malloc(s); 20 21 FILE* pF; 22 fopen_s(&pF, g_FileName, "a"); 23 24 if (!p) 25 sprintf_s(g_Buf, _BUF_SIZE, g_AllocateFail, g_AllocateNum, g_FreeNum); 26 else 27 { 28 g_AllocateNum++; 29 sprintf_s(g_Buf, _BUF_SIZE, g_AllocateOK, p, s, g_AllocateNum, g_FreeNum); 30 } 31 32 fwrite(g_Buf, sizeof(char), strlen(g_Buf), pF); 33 fflush(pF); 34 fclose(pF); 35 return p; 36 } 37 38 void operator delete(void* p) 39 { 40 free(p); 41 g_FreeNum++; 42 43 FILE* pF; 44 fopen_s(&pF, g_FileName, "a"); 45 46 sprintf_s(g_Buf, _BUF_SIZE, g_FreeOK, p, g_AllocateNum, g_FreeNum); 47 fwrite(g_Buf, sizeof(char), strlen(g_Buf), pF); 48 fflush(pF); 49 fclose(pF); 50 } 51 52 void* operator new[](size_t s) 53 { 54 return operator new(s); 55 } 56 57 void operator delete[](void* p) 58 { 59 operator delete(p); 60 } 61 62 #endif