How to Use valgrind to detect memory leakage in Linux

Source: Internet
Author: User
Tags valgrind
This article from valgrind official site of the "Quick Start Guide", it is recommended that readers directly to their website for more detailed information: http://www.valgrind.org/docs/manual/quick-start.html#quick-start.prepare 1. Introduction

The valgrind tool suite provides a number of debugging and profiling tools that help you make your programs faster and more correct. the most popular of these tools is called memcheck. it can detect Memory-related errors that are common in C and C ++ programs and that can lead to crashes and unpredictable behaviour.

The rest of this guide gives the minimum information you need to start detecting memory errors in your program with memcheck. For full documentation of memcheck and the other tools, please read the user manual.

2. Preparing your program

Compile your program-gTo include debugging information so that memcheck's error messages include exact line numbers. Using-O0Is also a good idea, if you can tolerate the slowdown.-O1Line numbers in error messages can be inaccurate, although generally speaking running memcheck on code compiled-O1Works fairly well. Use-O2And above is not recommended as memcheck occasionally reports uninitialised-value errors which don't really exist.

3. Running your program under memcheck

If you normally run your program like this:

  myprog arg1 arg2

Use this command line:

  valgrind --leak-check=yes myprog arg1 arg2

Memcheck is the default tool.--leak-checkOption turns on the detailed memory leak detector.

Your program will run much slower (eg. 20 to 30 times) than normal, and use a lot more memory. memcheck will issue messages about memory errors and leaks that it detects.

4. interpreting memcheck's output

Here's an example C program, in a file called A. C, with a memory error and a memory leak.

  #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;  }

Most error messages look like the following, which describes problem 1, the heap block overrun:

  ==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)

Things to notice:

  • There is a lot of information in each error message; read it carefully.

  • The 19182 is the process ID; it's usually unimportant.

  • The first line ("invalid write...") tells you what kind of error it is. Here, the program wrote to some memory it shocould not have due to a heap block overrun.

  • Below the first line is a stack trace telling you where the problem occurred. stack traces can get quite large, and be confusing, especially if you are using the C ++ STL. reading them from the bottom up can help. if the stack trace is not big enough, use--num-callersOption to make it bigger.

  • The Code addresses (eg. 0x804838f) are usually unimportant, but occasionally crucial for tracking down weirder bugs.

  • Some error messages have a second component which describes the memory address involved. this one shows that the written memory is just past the end of a block allocated with malloc () on line 5 of example. c.

It's worth fixing errors in the order they are reported, as later errors can be caused by earlier errors. Failing to do this is a common cause of difficulty with memcheck.

Memory Leak messages look like this:

  ==19182== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1  ==19182==    at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130)  ==19182==    by 0x8048385: f (a.c:5)  ==19182==    by 0x80483AB: main (a.c:11)

The stack trace tells you where the leaked memory was allocated. memcheck cannot tell you why the memory leaked, unfortunately. (ignore the "vg_replace_malloc.c", that's an implementation detail .)

There are several kinds of leaks; the two most important categories are:

  • "Definitely lost": Your program is leaking memory -- fix it!

  • "Probably lost": Your program is leaking memory, unless you're doing funny things with pointers (such as moving them to point to the middle of a heap block ).

Memcheck also reports uses of uninitialised values, most commonly with the message "Conditional jump or move depends on uninitialised value (s )". it can be difficult to determine the root cause of these errors. try using--track-origins=yesTo get extra information. This makes memcheck run slower, but the extra information you get often saves a lot of time figuring out where the uninitialised values are coming from.

If you don't understand an error message, please consult explanation of error messages from memcheck in the valgrind User Manual which has examples of all the error messages memcheck produces.

5. caveats

Memcheck is not perfect; it occasionally produces false positives, and there are mechanisms for suppressing these (see suppressing errors in the valgrind User Manual ). however, it is typically right 99% of the time, so you should be wary of ignoring its error messages. after all, you wouldn't ignore warning messages produced by a compiler, right? The suppression mechanic is also useful if memcheck is reporting errors in library code that you cannot change. The default suppression set hides a lot of these, but you may come into Ss more.

Memcheck cannot detect every memory error your program has. for example, it can't detect out-of-range reads or writes to arrays that are allocated statically or on the stack. but it shocould detect assumerrors that cocould crash your program (eg. cause a segmentation fault ).

Try to make your program so clean that memcheck reports no errors. once you achieve this state, it is much easier to see when changes to the program cause memcheck to report new errors. experience from several years of memcheck use shows that it is possible to make even huge programs run memcheck-clean. for example, large parts of Kde, OpenOffice.org and Firefox are memcheck-clean, or very close to it.

6. More information

Please consult the valgrind FAQ and the valgrind user manual, which have much more information. Note that the other tools in the valgrind distribution can be invoked with--toolOption.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.