笔者也是最近去面试被问到怎么做内存泄漏检查,之前都是靠人工屏蔽代码、或者PC-link/KW一类的检查工具进行检查,回来后搜索了下,才知道linux自带的就有mtrace工具。
具体操作步骤如下:
1.在linux下创建test.c文件,编写如下代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #include <mcheck.h> 6 7 8 int main() 9 { 10 setenv("MALLOC_TRACE","malloc.log",1); 11 mtrace(); 12 13 14 char* text = (char*)malloc(sizeof(char)*100); 15 memset(text,0,100); 16 memcpy(text,"hello,world!",12); 17 printf("%s\n",text); 18 return 0; 19 }
2.保存退出后用,gcc -g text.c -o test.out进行编译;
3.执行./test.out
4.执行命令mtrace test.out malloc.log,2-4步骤的结果如下
[email protected]:~$ gcc -g test.c -o test.out [email protected]-virtual-machine:~$ ./test.out hello,world! [email protected]-virtual-machine:~$ mtrace test.out malloc.log - 0x0000000000700010 Free 4 was never alloc‘d 0x7fc09fee4e9d - 0x0000000000700210 Free 5 was never alloc‘d 0x7fc09ffaf91f - 0x0000000000700230 Free 6 was never alloc‘d 0x7fc0a001f23c Memory not freed: ----------------- Address Size Caller 0x00000000007006a0 0x64 at /home/wqb/test.c:14 [email protected]-virtual-machine:~$
其中0x00000000007006a0 0x64 at /home/wqb/test.c:14 表明test.c的14行有内存泄漏。
原文地址:https://www.cnblogs.com/biaodi1900/p/9249406.html
时间: 2024-11-05 20:45:00