mtrace检查内存泄露
mtrace内存泄漏检测:
1. 安装mtrace命令:
yum install glibc-utils
2. 示例代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> /* mtrace 头文件 */ #include <mcheck.h> int main(int argc, char *argv[]) {
/* 设置环境变量, mtrace保存位置 */ setenv("MALLOC_TRACE", "mtrace_output.txt", 1); mtrace(); /* 打开 */ char *buff = NULL; int size = 128; buff = malloc(size); if (NULL == buff) return -1; memset(buff, 0, size); sprintf(buff, "hello, world."); printf("malloc buff:%s\n", buff); if (argc > 1) { printf("free buff.\n"); free(buff); } muntrace(); /* 关闭 */ return 0; }
3. 编译运行和检查结果
[root@localhost test]# gcc -g mtrace.c -o mtrace_test [root@localhost test]# ./mtrace_test malloc buff:hello, world. [root@localhost test]# mtrace mtrace_test mtrace_output.txt Memory not freed: ----------------- Address Size Caller 0x0000000001e435c0 0x80 at /root/test/mtrace.c:15 [root@localhost test]# [root@localhost test]# ./mtrace_test 123 malloc buff:hello, world. free buff. [root@localhost test]# mtrace mtrace_test mtrace_output.txt No memory leaks. [root@localhost test]#