Use Valgrind to Solve Memory Leak Issues in Linux

When developing programs under Linux, especially server-side programs, it is always in a loop. If it is found that there is no problem when the program first runs, but after a period of time, the program stops. The high probability of this situation is a memory leak.

Step 1:

We can use a simple command “free -m” to check whether it is really a memory leak. As shown below: If the memory usage is increasing and the free is decreasing as the program runs, it can be preliminarily identified as a memory leak.

       total     used     free    shared     buff/cache     available
Mem:   898      557       81        20       259            146
Swap:  1021     327       694

Step 2:


In order to prevent memory leaks caused by other running programs in the system, we can use another tool to know more precisely whether our program has a memory leak.

We can use “pmap -x <pid>” command to see the result. The pid can be obtained through the “top” command. In this way, we can always look at the program we are running and this tool can also see the stack and heap allocation.

Suppose, we have a piece of code like this:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    while (1) {
        char *str = malloc(5);
        printf("malloc again\n");
    }
    return 0;
}

We use “pmap -x 20521” command to see the result. 20521 is the pid.

20521: ./a.out
Address              Kbytes       RSS      Dirty     Mode       Mapping
0000000000400000     4            4        0         r-x--      a.out
0000000000400000     0            0        0         r-x--      a.out
... ...
000000000224a000     180972       180972   180972    rw---      [ anon ]
000000000224a000     0            0        0         rw---      [ anon ]
... ...
00007ffff978a000     132          12       12        rw---      [ stack ]
... ...
---------------- ------- ------- -------
total kB             185196       182128   181048

The RSS (Resident Set Size) in the result is closer to the size of the actual memory used by the computer. [anon] in mapping column indicates that it is allocated on the heap, which is also consistent with our code. As our program runs, we will find that more and more heaps are allocated, which means that our program has a memory leak.

This program was specially written by me, so it can be seen at a glance that the memory leak is because I have been malloc, but did not call free to release them. In many cases, it is easy to find the memory leak caused by without releasing malloc.

But sometimes, when we call other functions, such as the regcomp() function, there is a implicit memory allocatation process in this function.but because I did not call regfree to release, it caused a memory leak, which is more difficult to find.

Next, I will introduce how to download and install this tool.

Download and Install Valgrind

Method one:

  • wget http://valgrind.org/downloads/valgrind-3.4.1.tar.bz2
  • tar xvf  [FileName].tar.bz2
  • cd  [Unzipped directory]
  • ./configure
  • make
  • sudo make install

Method two:

  • sudo apt-get install valgrind

It is said that this method is very slow. So I used method one.

But there is a problem with method one that is some dependencies, it does not follow the installation, so there will be an error when using it, the error message prompts you to say that xxx is missing. Then, at this time, just running “sudo apt-get install xxx” command is OK.

Then I can start to introduce this tool and how to use it.

Valgrind Usage

  1. Valgrind is a toolkit that helps us locate errors faster, make development faster, and make the application more correct. One of the most popular tools is MemCheck.It can detect many of the memory-related errors common in C/C++ that can cause a program to crash or have unpredictable results. This is the Memcheck tool that we’re going to use.
  2. In order for MemCheck to extract some debug information, we add -g when compiling the program. For example, if it is normally “gcc xxx.c“, then we are now “gcc -g xxx.c“.
  3. If we run a program normally is “./myprog arg1 arg2“. Now we are going to use “Valgrind –leak-check=yes./myprog arg1 arg2” command to run this program.

Let me give you an example, an example from the official webiste.

  #include <stdlib.h>

  void f(void)
  {
     int* x = malloc(10 * sizeof(int));
     x[10] = 0;        // problem 1: heap block overrun
  }                    // problem 2: memory leak -- x not freed

  int main(void)
  {
     f();
     return 0;
  }

The result is:

  ==19182==    Invalid write of size 4
  ==19182==    at 0x804838F: f (example.c:6)
  ==19182==    by 0x80483AB: main (example.c:11)
  ==19182==    Address 0x1BA45050 is 0 bytes after a block of size 40 alloc'd
  ==19182==    at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130)
  ==19182==    by 0x8048385: f (example.c:5)
  ==19182==    by 0x80483AB: main (example.c:11)

Again, this tool is really powerful. And as you can see from the results, it’s very straightforward and precise, it finds the errors that are illegal, and it tells you in which function and in which line. It gets more and more precise from the bottom up, so let’s say we start with main, and then we start with f function. The following memory is not free is also directly pointed out. Such a handy tool is really worth spreading the word.


Have a good day! Any feedback is welcome.

Reference:

For more information, you can visit the website: http://valgrind.org/docs/manual/QuickStart.html

Share this article to your social media
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments