Detect memory leaks on macOS
For command line applications
Sometimes you may found yourself writing small programs on C/C++ on macOS. If you are a programmer, who cares about system resources you will probably want to know if your program loose pieces of memory. In other words, you may want to find memory leaks.
In 2020 macOS has a quietly powerful and handy tool to find memory leaks — leaks
. For some reason, the documentation is not very clear in the first reading, and it may take some time to figure out what you have to do to make it work properly. In this short piece, we will consider how to make it work and test it. Let’s go.
The code
At first, let’s create a simple program that definitely leaks some memory. Here you go:
At line #5 we allocate some memory and don’t call free()
function for it. It’s a memory leak. Save this program in any text editor and compile it. In terminal type:
In line #2 we compile our program. It will create an executable binary called leaker
. Then we run a system leaks
tool to find out if the program leaks memory calling line #5. Pay your attention that there is | grep LEAK:
command. We use it to short leaks
output to see only lines with leaks if they are there. If you want to see the whole output, just remove this command.
When you run line #5 you may see an error:
dyld: could not load inserted library ‘/usr/local/lib/libLeaksAtExit.dylib’ because image not found
It’s because leaks
did not find libLeaksAtExit.dylib
library. You need to run run lines #8–9 in this case. Please do; it doesn’t hurts even it needs sudo
run.
If you are lucky enough you should see output like this:
It means there is a memory leak, and we successfully detected it. Try to play with the code and call function free()
for the pointer and rebuild the program and try to detect the memory leak again.
Conclusion
That’s pretty it, a simple example of a complicated topic. I hope you will find this approach useful while you will write your programs. You may find more information about how leaks work in official man documentation.
Happy coding.