Detecting Memory Leaks
Any long-running application has to manage memory correctly, or eventually it’ll use up all available memory and crash. If you use a language that handles this automatically for you, congratulations. If you program in C or C++ or any other language where you’re responsible for memory management, here’s a short tutorial on using valgrind, which, among other things, will report on any leaks your programs have:
To install valgrind, such as on Ubuntu or Debian, issue:
sudo apt-get install valgrind
By default, ØMQ will cause valgrind to complain a lot. To remove these warnings, create a file called valgrind.supp that contains this:
{
<socketcall_sendto>
Memcheck:Param
socketcall.sendto(msg)
fun:send
...
}
{
<socketcall_sendto>
Memcheck:Param
socketcall.send(msg)
fun:send
...
}Fix your applications to exit cleanly after Ctrl-C. For any application that exits by itself, that’s not needed, but for long-running applications, this is essential. Otherwise, valgrind will complain about all currently allocated memory.
Build your application with -DDEBUG, if it’s not your default setting. That ensures valgrind can tell you exactly where memory is being leaked.
Finally, run valgrind as follows (all on one line)
valgrind --tool=memcheck --leak-check=full --suppressions=valgrind.supp
someprogAfter fixing any errors it reports, you should get the pleasant message:
==30536== ERROR SUMMARY: 0 errors from 0 contexts...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access