I also recently went to interview was asked how to do the memory leak check, before all rely on artificial shielding code, or pc-link/kw a class of inspection tools to check, back after the search, just know that Linux comes with mtrace tools.
The following are the steps:
1. Create the test.c file under Linux and write the following code:
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5#include <mcheck.h>6 7 8 intMain ()9 {TenSetenv"Malloc_trace","Malloc.log",1); One mtrace (); A - - Char* Text = (Char*)malloc(sizeof(Char)* -); thememset (Text,0, -); -memcpy (Text,"hello,world!", A); -printf"%s\n", text); - return 0; +}
2. Save and exit after use, Gcc-g text.c-o test.out to compile;
3. Execution./test.out
4. The result of executing the command mtrace test.out malloc.log,2-4 step is as follows
[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-0x0000000000700010Free4Was never alloc'D 0x7fc09fee4e9d-0x0000000000700210Free5Was never alloc'D 0x7fc09ffaf91f-0x0000000000700230Free6Was never alloc'D 0x7fc0a001f23cMemory not freed:-----------------Address Size Caller0x00000000007006a0 0x64AT/HOME/WQB/TEST.C: -[email protected]-virtual-machine:~$
Where 0x00000000007006a0 0x64 at/home/wqb/test.c:14 indicates that 14 rows of test.c have a memory leak.
Linux c program memory Leak Detection Tool-mtrace tool Introduction