Finding and fixing memory issues using Valgrind with example of Apache+FastCGI web application


Code reviews and walkthrough help a lot in maintaining a tab on coding practice and allocation/freeing of memory in a application. But over a period of time an application grows with additional number of features being added over a period of time. So it’s always better to have an automated solution to find any memory related issue with your application.

Valgrind is a great tool that helps you do that. For information about valgrind please refer to following links:

Valgrind quick start guide:
Complete user manual:

A simple example of using Valgrind to detect memory issues with an Apache+FastCGI web app written in C on a Linux box.

Say that the FastCGI based web app is already in production and running on your servers and you want to use valgrind to check memory related issue, follow following steps.

First install valgrind on the machine where you want to run the web app with valgrind do following:

# wget –c “”

Replace with the latest available version (as bugs found with previous releases would have been fixed)

# bunzip2 valgrind-3.3.1.tar.bz2
# tar –xvf valgrind-3.3.1.tar
# cd valgrind-3.3.1
# ./configure
# make
# make install

If all the steps go thru properly valgrind will be built and installed in /usr/local/bin. Make sure that it’s in the PATH variable.

Now say the FastCGI configuration looks like in the httpd.conf file:

<IfModule mod_fastcgi.c>
FastCgiIpcDir /tmp/fcgi_ipc/
FastCgiServer htdocs/MyApp

Instead of changing the whole configuration just write a simple shell script in a directory other than the one containing the actual MyApp FastCGI application

# cat > MyApp
/usr/local/bin/valgrind -v –tool=memcheck –leak-check=full –log-file=/tmp/MyAppValgrind.log /path/to/my/app/ActualMyApp

Then press CTRL+D

Now stop Apache, move the MyApp (actual FastCGI application binary) to ActualMyApp.

Replace the existing MyApp with our new script, make sure it has execute permissions.

Start Apache, you are done. Valgrind will log the issue in /tmp/MyAppValgrind.log file

Note: Compile your program with -g to include debugging information so that Memcheck’s error messages include exact line numbers.

Information on Valgrind Memcheck error messages is available @

Happy debugging 🙂


No Responses Yet to “Finding and fixing memory issues using Valgrind with example of Apache+FastCGI web application”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: