How to use the memleak tool
This article describes how to use the memleak tool to find memory leaks.
Overview
To debug memory leaks, the memleak
tool from the bcc-tools
suite can be very useful.
It does not require to change the application like a lot of heap profilers require.
If the bcc-tools are not yet installed, they can be installed on arch linux with
|
|
The program also requires the linux-headers package. If the package is not yet installed, it can be installed with the following command:
|
|
Signs of memory leaks
Monitoring the RSS size and the virtual size of a process over time might give good hints if there is a potential memory leak. If the virtual size grows continuously at a faster pace as RSS, there is a high likelyhood that there is a memory leak. Another indiciation is if the memory size of the process does not stabilize and continues to grow.
Invoking the tool
The memleak tool can be invoked with the -c
switch to start the to be analyzed program
at the same time as the memleak tool. The other way is to attach the memleak tool with
the -p
switch to a running process.
Monitoring individual memory allocations
With the -t
switch individual allocations and de-allocations can be monitored. This is
very useful to see how much memory is allocated. These are the memory allocations that
are performed by the kernel on behalf of the process. The user space memory manager of
the process might process a lot more memory allocation and memory de-allocation requests.
The memleak tool does not report the user-space requests.
The tool can be invoked with:
|
|
The -t
flags specifies tracing of individual allocations and the -p
flag specifies
which process to trace.
The following gives an impression of the typical output:
|
|
The format of the output is: task, pid, cpu#, flags, timestamp and allocation / de-allocation message. For each allocation it shows the two lines: alloc entered and alloc exited. For the de-allocation operation it only shows the free entered entry. For the allocations as well as for the de-allocation it reports the address as well as the size of the request. This makes it very easy to write scripts on top of the output to see which memory addresses do not get freed.
In addition it also shows the process id and the name of the process. If the process starts new threads or child processes they are also traced.
This has already helped to find some memory leaks in server applications.
Capturing call stacks
If the user specifies the -a
option, the tool also captures the top call stacks of
the callers. Typical result is something like this:
|
|
Once potential leaks have been identified, this makes it easier to identify what code is reponsible for the allocation or de-allocation. There are additional flags to the memleak tool, which allow to report only allocations / de-allocations of a certain size.