leaks
command-line tool will report
like the following:
Process: checker [84357]
Path: /path/to/program
Load Address: 0x104703000
Identifier: checker
Version: ???
Code Type: X86-64
Parent Process: zsh [64610]
Date/Time: 2019-11-30 18:43:06.864 -0800
Launch Time: 2019-11-30 18:42:58.593 -0800
OS Version: Mac OS X 10.13.4 (17E199)
Report Version: 7
Analysis Tool: /usr/bin/leaks
Physical footprint: 300K
Physical footprint (peak): 300K
----
leaks Report Version: 3.0
Process 84357: 161 nodes malloced for 17 KB
Process 84357: 3 leaks for 64 total leaked bytes.
Leak: 0x7fdf5b400350 size=16 zone: DefaultMallocZone_0x10470e000
Leak: 0x7fdf5b4027c0 size=16 zone: DefaultMallocZone_0x10470e000
Leak: 0x7fdf5b402810 size=32 zone: DefaultMallocZone_0x10470e000
My question is, how can I use these information to actually track down and find which malloc calls in my source code doesn't have corresponding free()
calls?
How can I find out which source file / where in the source file?
Do I need to change the value of some environment variables like MallocStackLogging
or MallocStackLoggingNoCompact
?
Set environment variable MallocStackLogging
to true, run program, then run leaks
.
This will print a stack trace of where the leaked memory was allocated.
The way I did it is:
export MallocStackLogging=1
main
function, add the following code right before returning.system("leaks executablename");
. It took me a while, but once I figured this all out it works great:
valgrind
, until it couldn't run on my newer osx version. I was looking for a similarly convenient command-line approach to tracing memory leaks (could use Instruments instead, but it is heavyweight and UI-driven, both of which annoy me)leaks -atExit
tells me which leaks exist, but not where any leaked allocation came fromleaks -atExit
runs, obviously, at exit So you have to run MallocStackLogging, pause your program, then run leaks:
Open a terminal and set MallocStackLogging: export MallocStackLogging=1
At the end of the program, before it exists, add a line of code to pause it by reading from stdin, then recompile: fscanf(stdin, "c"); // wait for user to enter input from keyboard
fscanf(stdin, "c"); // wait for user to enter input from keyboard
Run your program and wait for it to pause
In a separate terminal, find your pid: ps aux | grep my_program_name
ps aux | grep my_program_name
Run leaks, and now it will output the leak allocations: leak <pid_from_above_step>
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.