使用一些宏替换,可以轻松地完成任务。
在任意C文件中,加入如下代码
#undef malloc
#undef realloc
#undef calloc
#undef free
#include "stdlib.h"//防止malloc/free被替换
void *jj01_malloc(unsigned int num_bytes,const char*fun ,int line)
{void * ret = malloc(num_bytes);fprintf(stderr,"[%s,%d]malloc %u %x",fun,line,num_bytes,(long)ret);return ret;
}
void *jj01_realloc(void *mem_address, unsigned int newsize,const char*fun ,int line)
{void * ret = realloc(mem_address,newsize);fprintf(stderr,"[%s,%d]realloc %u %x",fun,line,newsize,(long)ret);return ret;
}
void *jj01_calloc(size_t n, size_t size,const char*fun ,int line)
{void * ret = calloc(n,size);fprintf(stderr,"[%s,%d]calloc %u %x",fun,line,n*size,(long)ret);return ret;
}
void jj01_free(void * ptr,const char*fun ,int line)
{fprintf(stderr,"[%s,%d]free %x",fun,line,(long)ptr);free(ptr);
}
其实就是包装一下malloc/free相关函数,调用的时候打印一下日志。
typedef unsigned int size_t;
void *jj01_malloc(unsigned int num_bytes,const char*fun ,int line);
void jj01_free(void * ptr,const char*fun ,int line);
void *jj01_realloc(void *mem_address, unsigned int newsize,const char*fun ,int line);
void *jj01_calloc(size_t n, size_t size,const char*fun ,int line);#include "stdlib.h"
#define malloc(x) jj01_malloc((x),__FUNCTION__,__LINE__)
#define realloc(a,b) jj01_realloc((a),(b),__FUNCTION__,__LINE__)
#define calloc(a,b) jj01_calloc((a),(b),__FUNCTION__,__LINE__)#define free(x) jj01_free((x),__FUNCTION__,__LINE__)
这样就可以实现自动替换代码中的所有malloc/free
下一篇:七、延时队列