leak_detector_c/leak_detector_c.h
2025-04-23 16:07:47 +08:00

62 lines
1.9 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ifndef LEAK_DETECTOR_C_H
#define LEAK_DETECTOR_C_H
// 文件名最大长度
#define FILE_NAME_LENGTH 256
// 内存泄漏信息输出文件
#define OUTPUT_FILE "leak_info.txt"
// 用宏重定义 malloc、calloc 和 free为其添加文件名和行号信息
#define malloc(size) xmalloc (size, __FILE__, __LINE__)
#define calloc(elements, size) xcalloc (elements, size, __FILE__, __LINE__)
#define free(mem_ref) xfree(mem_ref)
// 用于记录每一次内存分配的信息结构体
struct _MEM_INFO {
void *address; // 分配的内存地址
unsigned int size; // 分配的大小
char file_name[FILE_NAME_LENGTH]; // 分配发生的文件名
unsigned int line; // 分配发生的代码行号
};
typedef struct _MEM_INFO MEM_INFO;
// 内存泄漏记录结构体,使用链表形式组织
struct _MEM_LEAK {
MEM_INFO mem_info; // 内存信息
struct _MEM_LEAK *next; // 指向下一个节点的指针
};
typedef struct _MEM_LEAK MEM_LEAK;
// 添加一条内存分配信息记录
void add(MEM_INFO alloc_info);
// 删除某个位置的内存记录
void erase(unsigned pos);
// 清空所有内存记录
void clear(void);
// 自定义 malloc记录内存分配位置
void *xmalloc(unsigned int size, const char *file, unsigned int line);
// 自定义 calloc记录内存分配位置
void *xcalloc(unsigned int elements, unsigned int size, const char *file, unsigned int line);
// 自定义 free在释放内存时移除记录
void xfree(void *mem_ref);
// 添加一条内存分配记录
void add_mem_info(void *mem_ref, unsigned int size, const char *file, unsigned int line);
// 移除某个内存记录(在调用 free 时使用)
void remove_mem_info(void *mem_ref);
// 生成内存泄漏报告
extern void report_mem_leak(void);
extern void dump_mem_leak(void);
#endif