How to Run Valgrind in CLion, for C and C++ Programs

I needed this for myself, and Googled around but didn't find anything satisfactory, but now after a little work, I'm all set with Valgrind.

Wouldn't you love this on your toolbar?

Valgrind for C on CLion toolbar

Well, you can have it, friend. Read on.

1. Add this Bash script

I have it in my current project, because I've got multiple subprojects in one project, but you can put this script in your home directory or wherever.

valgrind.sh

#!/usr/bin/env bash

if [ $1 = "C" ]  
then  
    /usr/bin/clang -ggdb main.c -std=c99 -Wall -Werror -o program && /usr/local/bin/valgrind ./program
elif [ $1 = "Cpp" ]  
then  
    /usr/bin/clang++ -std=c++11 -stdlib=libc++ main.cc -Wall -Werror -o program && /usr/local/bin/valgrind ./program
fi

What it does: The script takes the string C or Cpp as an argument. It then compiles your program and runs Valgrind on the executable.

Make it executable: chmod +x valgrind.sh

Update the script as necessary. This script handles both C and C++. It uses main.c for C and main.cc for C++.

2. Add it to CLion as an external tool

Go to Preferences > Tools > External Tools.

CLion Preferences Tools External Tools

Click the + to add an external tool.

Setting up a new external tool for CLion

  • Fill in a name.
  • Enter the path to valgrind.sh.
  • Add C or Cpp as a parameter. This will run Valgrind the right way for your language. I made one for C, and then duplicated the external tool and changed the copy to Cpp.
  • Set the working directory to the macro $FileDir$ which will run the command in whatever directory (or file) you happen to have in focus.

3. Add the button to your toolbar

By default, the tool you just made lives under Tools (on main menu) > External Tools. But navigating to that every time stinks.

Right-click your toolbar, click Customize Menus and Toolbars.

Customize Menus and Toolbars

Click Main Toolbar.

Main Toolbar

Find the spot where you want to add the icon. Select an item and click Add After...

Add after to add icon

Now you have to find the tool to add there. Click External Tools.

External Tools

Select it and click OK. it will complain that there's no icon. That's OK. The default is a cute green alien.

Select the tool

And it's been added!

Valgrind added to CLion main menu

4. Push the button

Valgrind for C on CLion toolbar

Now when you click the button, it will compile in the working directory and run Valgrind on your executable.

Running Valgrind in CLion on a C program

Note the lost memory there is not part of my program's memory, as some by-product of running it on a Mac. On Linux lost memory is all 0. I keep my eye on these only on Mac:

  • definitely lost
  • indirectly lost

Play around with not freeing memory and you'll see what I mean.

Enjoy!

comments powered by Disqus