Skip to main content

How to quickly investigate memory leak in your application

Every C/C++ software developer meet problem of memory leak (allocating memory over time which is not freed). If you would like to know how to investigate memory leak problem in your application, this article is for you. For memory leak investigation I recommend to use valgrind tool. Especially with it's Massif tool. Let's see the example how we could use that tool for memory leak investigation. Below snippet of code has lots of points where memory leak can occur.
 1 #include <stdio.h>
 2 
 3 void allocmem1()
 4 {
 5     char* memleak2 = malloc(100*sizeof(char));
 6 }
 7 
 8 void allocmem2()
 9 {
10     char* memleak2 = malloc(10*sizeof(char));
11     allocmem1();
12 }
13 
14 void allocmem3()
15 {
16     char* memleak2 = malloc(5*sizeof(char));
17     allocmem2();
18 }
19 
20 int main(int argc, const char **argv)
21 {
22     char* memleak1 = malloc(5*sizeof(char));
23     char* memfreed = malloc(5*sizeof(char));
24 
25     int i=0;
26     for (i=0; i<100; i++){
27       allocmem3();
28     }
29 
30     free(memfreed);
31     return 0;
32 }
33 
34 
First, save above code in main.c file and compile it:
gcc main.c  -o main
Next, examine memory leak occurances using valgrind tool:
valgrind --tool=massif ./a.out
Output of above command should be empty for our example. However, notice that new file has been created in the directory where you invoked valgrind from (massif.out.PID). That file contaisn valgrind data which we will use for our memory leak investigation. Let's make that data human readable. Use ms_print tool for it:
ms_print massif.out.PID
Output of ms_print command allows you to detect where your memory leak are. On the top of that output, you see the graph of memory usage where you can quickly see that we have memory leak. It should look like this one:
 1 
 2     KB
 3 16.45^                                 #
 4      |                                 #
 5      |                                :#
 6      |                                @#
 7      |                                @#
 8      |                                @#
 9      |                               :@#
10      |                               @@#
11      |                               @@#
12      |                              @@@#
13      |                              @@@#
14      |                              @@@#
15      |                             @@@@#
16      |                             @@@@#
17      |                             @@@@#
18      |                            :@@@@#
19      |                            @@@@@#
20      |                            @@@@@#
21      |                           :@@@@@#
22      |                           :@@@@@#
23    0 +--------------------------------->ki
24      0                                                                   143.3
25 
Below, you have reports of which functions, how what amount of memory allocates over time. We have multiple memory leaks in our example. Let's focus on following repeating statement:
 1 
 2 ->58.39% (2,200B) 0x400596: allocmem1 
 3 | ->58.39% (2,200B) 0x4005BC: allocmem2 
 4 |   ->58.39% (2,200B) 0x4005DE: allocmem3 
 5 |     ->58.39% (2,200B) 0x400625: main 
 6 ...
 7 67.82% (3,695B) 
 8 ->58.74% (3,200B) 0x400596: allocmem1 
 9 | ->58.74% (3,200B) 0x4005BC: allocmem2 
10 |   ->58.74% (3,200B) 0x4005DE: allocmem3 
11 ...
12 ->59.15% (6,700B) 0x400596: allocmem1 
13 | ->59.15% (6,700B) 0x4005BC: allocmem2 
14 |   ->59.15% (6,700B) 0x4005DE: allocmem3 
15 |     ->59.15% (6,700B) 0x400625: main 
16 ...
17 ->59.35% (10,000B) 0x400596: allocmem1 
18 | ->59.35% (10,000B) 0x4005BC: allocmem2 
19 |   ->59.35% (10,000B) 0x4005DE: allocmem3 
20 |     ->59.35% (10,000B) 0x400625: main 
That statement contains function which allocates memory (ex. allocmem1) and its caller functions. We can quickly see that memory allocated by fucntion allocmem1 increases with time (2,200B, 3,695B, 6,700B ...). *It indicates memory leak*. Now you can see that for our example we have memory leak in function allocmem1. Try to analyze remaining output statements and deduct where other memory leak exists That's it. Hopefully this quick example shows you how to quickly investigate memory leaks in your application using Valgrind tool. I encourage you to experiment with creating your own memory leak samples and investigateing them using Valgrind _ Massif. More info about valgrind + massif investigation can be found here: Valgrind + Massif Good luck with your memory leak investigation. Picture source: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiL3BWmd_5_7HRaYyW_jOdqfJaQtF-IcSeT4pxHFQl-qon2WynXAOFUJ49hQwnHAMkso8bR7kfoGtxPXuuW2LB8uYS9gWOcFSMH8ukH9z6oOrevfN43HcxhtYLnwwc6PIXyGoXw63svNSeN/s640/memoryleak+1.png

Comments

Popular posts from this blog

GDB Automatic Deadlock Detector

Have you ever had a problem with detection deadlock between threads in your C/C++ application? Would you like to do that automatically? Try this GDB Automatic Deadlock Detector from my github: GDB Automatic Deadlock Detector Picture source: http://csunplugged.org/wp-content/uploads/2015/03/deadlock.jpg1286488735

STL - count and count_if algorithms

One of the basic and most useful STL algorithms is algorithm which can be used to count number of elements within selected container according to specified criteria. In order to do that we can use std::count or std::count_if algorithm. std::count (firstElementIterator, lastElementIterator, elementForSearch) - is function which will go through container using firstElementIterator and lastElementIterator and return number of container elements which value is equal elementForSearch std::count_if (firstElementIterator, lastElementIterator, UnaryPredicateFunction) - is function which examine range from firstElementIterator to lastElementIterator and return number of container elements which fulfill UnaryPredicateFunction criteria. UnaryPredicateFunction is function having following signature: bool functionName(const Type& a) . So, count_if returns number of elements where UnaryPredicateFunction returns true for. For better understanding let's take a

Advanced C++ - Stack unwinding

Stack unwinding is normally a concept of removing function entries from call stack (also known as Execution stack, Control stack, Function stack or Run-time stack). Call Stack is a stack data structure that stores active functions' addresses and helps in supporting function call/return mechanism. Every time when a function is called, an entry is made into Call stack which contains the return address of the calling function where the control needs to return after the execution of called function. This entry is called by various names like stack frame , activation frame or activation record. With respect to exception handling , stack Unwinding is a process of linearly searching function call stack to reach exception handler. When an exception occurs, if it is not handled in current function where it is thrown, the function Call Stack is unwound until the control reaches try block and then passes to catch block at the end of try block to handle exception. Also, in this proc