1:通过宏定义 FILE__和__LINE 获取文件和行号信息;
2:通过把原始malloc封装一下,实现 FILE__和__LINE 的打印;
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
// 要使用 __FILE__和__LINE__ 关键字
#define Malloc2(size) DqMalloc(size, __FILE__, __LINE__)
#define Free2(ptr) DqFree(ptr, __FILE__, __LINE__)
// 可以把使用malloc的文件名和行号打印出来
void *DqMalloc(int size, const char *filename, int line)
{
void *ret = malloc(size);
// 如果文件名太长,就需要用语法过滤一下
printf("malloc-info file_name=%s, line = %d, addr = %08p, size = %d\n", filename, line, ret, size);
return ret;
}
void DqFree(void *ptr, const char *filename, int line)
{
printf("free-info file_name=%s, line = %d, addr = %08p \n", filename, line, ptr);
free(ptr);
}
int main (void)
{
printf("hello world \r\n");
void *ptr = Malloc2(1024);
Free2(ptr);
return 0;
}
3:使用VSCODE运行一下代码
下面是gcc编译过程和世纪的运行日志
[Running] cd "c:\Users\duqiu\Desktop\project\C\" && gcc malloc.c -o malloc && "c:\Users\duqiu\Desktop\project\C\"malloc
hello world
malloc-info file_name=malloc.c, line = 28, addr = 0000000000B01420, size = 1024
free-info file_name=malloc.c, line = 30, addr = 0000000000B01420
[Done] exited with code=0 in 1 seconds