Valgrind Your Memory Leaks Away

Valgrind Your Memory Leaks Away

 

valgrind

If you are not already familiar with using Valgrind, it is an excellent tool for finding and debugging pesky memory leaks in C and C++ programs.  Even the smallest memory leak can cause a high performance application to crash over time.

So what happens when you test your application with Valgrind’s Memcheck tool and it tells you that you are leaking memory left and right?  This is never a good feeling, but don’t worry, it happens to the best of us.  The first thing to keep in mind is that many memory leaks reported by Valgrind are actually false positives (let’s be optimistic and give ourselves the benefit of the doubt), so we’ll want to check out their documentation and double (maybe even triple) check to make sure that we’ve set all the parameters for Valgrind correctly for our testing environment before we run it again.

Using Valgrind to check the WURFL InFuze NGINX Module without setting any parameters will report a number of memory leaks, but in real world tests the module works perfectly. Valgrind’s documentation recommends to test against an executable compiled in debug mode, without any optimization by setting -O as a parameter from the Command Line Interface.

If you do not specify the Valgrind option –run-libc-freeres=no the finalizers will not be called leaving most of the memory allocated, causing memory leaks to be reported in the standard C++ library.  NGINX will also need some specific configurations in order to run correctly under Valgrind, as you can see from this official NGINX forum link.

 

#user nobody;
worker_processes  1;
daemon off;
master_process off;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
events {
      worker_connections  1024;
}
 
http {
     include       mime.types;
     default_type  application/octet-stream;
 
     ##########################################
     # Rest of your configuration goes here ...
     ##########################################
}
With this setup Valgrind will keep the NGINX process up and running until you gracefully stop it by typing kill -TERM valgrindPID, where valgrindPID is the Valgrind’s process identifier.