When developing Nokogiri, the most valuable tool I use to track down memory-related errors is Valgrind. It rocks! Aaron and I run the entire Nokogiri test suite under Valgrind before releasing any version.

I could wax poetic about Valgrind all day, but for now I'll keep it brief and just say: if you write C code and you're not familiar with Valgrind, get familiar with it. It will save you countless hours of tracking down heisenbugs and memory leaks some day.

In any case, I've been meaning to package up my utility scripts and tools for quite a while. But they're so small, and it's so hard to make them work for every project ... it's looking pretty likely that'll never happen, so blogging about them is probably the best thing for everyone.

Basics

Oooh! But that's not actually what you want. The Matz Ruby Interpreter does a lot of funky things in the name of speed, like using uninitialized variables and reading past the ends of malloced blocks that aren't on an 8-byte boundary. As a result, something as simple as require 'rubygems' will give you 3800 lines of error messages (see this gist for full output).

Without going too far off-topic, I'd should just mention that those "leaks" aren't really leaks, they're characteristic of how the Ruby interpreter manages its internal memory. (You can see this by running this example with --leak-check=full.)

Rakified!

Here's an easy way to run Valgrind on your gem's existing test suite. This rake task assumes you've got Hoe 1.12.1 or higher.

Those basic options will give you a decent-sized stack walkback on errors, will make sure you see every error, and will skip all the BS output mentioned above. You can read Valgrind's documentation for more information, and to tune the output.

If you're not testing a gem, or don't have Hoe installed, try this for Test::Unit suites: