malloc函数C语言简单封装方便定位内存泄露
定义一个全局数组,数组大小为malloc枚举大小,枚举从0开始,每用一个malloc人为枚举名加1。封装一个my_malloc()函数,传入枚举名参数,函数中每调用一次,对应枚举名数组下标中的值++。封装一个my_free()函数, 传入枚举名参数,函数中每调用一次,对应枚举名数组下标中的值–。在定时器线程中定时轮询数组中的值,如果有某个枚举下标值不为0,打印出来,说明该枚举申请出有内存泄露。
/* mallocId */
typedef enum
{
LF_MALLOC_ID0 = 0,
LF_MALLOC_ID1,
LF_MALLOC_ID_SIZE
}LF_MALLOC_ID_E;
/* mallo申请ID号集合 */
static unsigned char gs_ucMallocId[LF_MALLOC_ID_SIZE] = {0};
/**
* @description: 带校验的malloc封装
* @param {LF_MALLOC_ID_E} eMallocId: malloc申请ID号
* @param {size_t} size: 内存申请大小
* @return {void*}申请内存地址
*/
void* LF_malloc(LF_MALLOC_ID_E eMallocId, size_t size)
{
gs_ucMallocId[eMallocId]++;
return malloc(size);
}
/**
* @description: 带校验的free封装
* @param {LF_MALLOC_ID_E} eMallocId: free申请ID号
* @param {void *} memblock: 内存地址
* @return {void}
*/
void LF_free(LF_MALLOC_ID_E eMallocId, void * memblock)
{
gs_ucMallocId[eMallocId]--;
free(memblock);
return;
}
/**
* @description: 定时校验内存申请是否泄露
* @return {int}iLeakCount:0无泄露, >0:泄露个数
*/
static int LF_malloc_time_check()
{
int iLeakCount = 0;
for(int i=0; i<LF_MALLOC_ID_SIZE; i++)
{
if(gs_ucMallocId[i] > 0)
{
iLeakCount++;
printf("memory leak!!! eMallocId[%d] gs_ucMallocId[%d]\n", i, gs_ucMallocId[i]);
}
}
printf("memory leak iLeakCount[%d]\n", iLeakCount);
return iLeakCount;
}
/**
* @description: 定时器线程,用于周期性操作、超时清除等。
* @param {void} *arg: 线程入参
* @return {NULL}
*/
void* LF_timer_thread(void *arg)
{
int iCount100ms = 0;
int iCount1s = 0;
printf("------------- timer_thread thread -------------\n");
prctl(PR_SET_NAME, "timer_thread");
while(1)
{
/*100ms基础时间步进*/
usleep(100 * 1000);
iCount100ms++;
/*500ms*/
//if(0 == (iCount100ms % 5))
//{
//
//}
/*1s*/
if(0 == (iCount100ms % 10))
{
iCount100ms = 0;
iCount1s++;
}
/*1min*/
if((iCount1s / 60) >= 1)
{
iCount1s = 0;
LF_malloc_time_check();
}
}
printf("LF_timer_thread end!\n");
return NULL;
}
{
char *pcDeviceName = NULL;
//pcDeviceName = (char*)malloc(64);
pcDeviceName = (char*)LF_malloc(LF_MALLOC_ID0, 64);
if (NULL == pcDeviceName)
{
printf("malloc error\n");
}
memset(pcDeviceName, 0, 64);
/*
内存使用
*/
if(NULL != pcDeviceName)
{
//free(pcDeviceName);
LF_free(LF_MALLOC_ID0, pcDeviceName);
pcDeviceName = NULL;
}
}