9. Massif: a heap profiler
To use this tool, you must specify
--tool=massif
on the Valgrind command line.
9.1. Overview
Massif is a heap profiler.
It measures how much heap memory your program uses.
This includes both the useful
space, and the extra bytes allocated for book-keeping and alignment purposes. It can also measure the size of your
program’s stack(s), although it does not do so by default.
Heap profiling can help you reduce the amount of memory your program uses.
On modern machines with virtual
memory, this provides the following benefits:
• It can speed up your program -- a smaller program will interact better with your machine’s caches and avoid paging.
• If your program uses lots of memory, it will reduce the chance that it exhausts your machine’s swap space.
Also, there are certain space leaks that aren’t detected by traditional leak-checkers, such as Memcheck’s.
That’s
because the memory isn’t ever actually lost -- a pointer remains to it -- but it’s not in use. Programs that have leaks
like this can unnecessarily increase the amount of memory they are using over time. Massif can help identify these
leaks.
Importantly, Massif tells you not only how much heap memory your program is using, it also gives very detailed
information that indicates which parts of your program are responsible for allocating the heap memory.
9.2. Using Massif and ms_print
First off, as for the other Valgrind tools, you should compile with debugging info (the
-g
option). It shouldn’t matter
much what optimisation level you compile your program with, as this is unlikely to affect the heap memory usage.
Then, you need to run Massif itself to gather the profiling information, and then run ms_print to present it in a readable
way.
9.2.1. An Example Program
An example will make things clear. Consider the following C program (annotated with line numbers) which allocates
a number of different blocks on the heap.
136