linux – finding memory leaks

Memory leaks are among the most difficult bugs to detect because they don’t cause any outward problems until you’ve run out of memory and your call to malloc suddenly fails. In fact, when working with a language like C or C++ that doesn’t have garbage collection, almost half your time might be spent handling correctly freeing memory. And even one mistake can be costly if your program runs for long enough and follows that branch of code.

When you run your code, you’ll need to specify the tool you want to use; simply running valgrind will give you the current list. We’ll focus mainly on the memcheck tool for this tutorial as running valgrind with the memcheck tool will allow us to check correct memory usage. With no other arguments, Valgrind presents a summary of calls to free and malloc: (Note that 18490 is the process id on my system; it will differ between runs.)

valgrind –tool=memcheck program_name

If you have a memory leak, then the number of allocs and the number of frees will differ (you can’t use one free to release the memory belonging to more than one alloc). We’ll come back to the error summary later, but for now, notice that some errors might be suppressed — this is because some errors will be from standard library routines rather than your own code.

If the number of allocs differs from the number of frees, you’ll want to rerun your program again with the leak-check option. This will show you all of the calls to malloc/new/etc that don’t have a matching free.

Memcheck provides command line options that can be used to focus the checking process. Some of the options available are:
–leak-check
When enabled, Memcheck searches for memory leaks when the client program finishes. The default value is summary, which outputs the number of leaks found. Other possible values are yes and full, both of which give details of each individual leak, and no, which disables memory leak checking.
–undef-value-errors
When enabled (set to yes), Memcheck reports errors when undefined values are used. When disabled (set to no), undefined value errors are not reported. This is enabled by default. Disabling it speeds up Memcheck slightly.
–ignore-ranges
Allows the user to specify one or more ranges that Memcheck should ignore when checking for addressability. Multiple ranges are delimited by commas, for example, –ignore-ranges=0xPP-0xQQ,0xRR-0xSS.

Leave a Reply

Your email address will not be published. Required fields are marked *