Prevent memory leaks Linux with Valgrind for inspection __linux

Source: Internet
Author: User
Tags valgrind

One of the most troubling problems with C + + is memory management, and sometimes it takes days to find a memory leak or a memory access crossing, and if there is a tool that can help us do this, Valgrind is just one of those tools.

Valgrind is a software suite that runs on the x86, AMD64, and PPC32 architectures based on a simulation Linux program debugger and profiler. Valgrind contains a core that provides a virtual CPU run program and a series of tools that perform debugging, profiling, and similar tasks. Valgrind is highly modular, so developers or users can add new tools to it without damaging their own structures.

Valgrind's official web site is: http://valgrind.org

You can download the latest valgrind on its website, which is open source and free.

First, introduce

Valgrind contains several standard tools, which are:

1, Memcheck

Memcheck the problem of memory management in the probe program. It checks all read/write operations on memory and intercepts all malloc/new/free/delete calls. The Memcheck tool can therefore detect the following problems:

1 Use uninitialized memory

2 read/write memory that has been freed

3 read/write memory out of bounds

4 read/write inappropriate memory stack space

5) Memory leak

6) do not match using malloc/new/new[] and free/delete/delete[.

2, Cachegrind

Cachegrind is a cache profiler. It simulates the L1, D1, and L2 cache in the execution CPU, so it can pinpoint the cache misses in the code. If you need it, it can print out the number of cache misses, memory references, and every line of code that occurs cache misses, each function, every module, and the entire program's summary. If you require more detailed information, it can print out the number of misses per line of machine code. On x86 and AMD64, cachegrind through CPUID automatic detection machine cache configuration, so in most cases it no longer need more configuration information.

3, Helgrind

Helgrind find competitive data in multithreaded programs. Helgrind looks for memory addresses, memory addresses that are accessed by more than one thread, but is detected without using a consistent lock. This means that these addresses are not synchronized when they are accessed by multiple threads, and are likely to cause a timing problem that is difficult to find.

What did Valgrind do to your program?

Valgrind is designed to be non-intrusive and works directly on executables, so you don't need to recompile, connect, and modify your program before checking it out. To check a program is simple, you just have to execute the command below.

Valgrind--tool=tool_name program_name

For example, we need to do a memory check on the ls-l command, just execute the following command.

Valgrind--tool=memcheck Ls-l

Regardless of which tool you use, Valgrind always gets control of your program before it starts, and reads debug information from the Executable Association library. Then, running the program on the virtual CPU provided by the Valgrind core, Valgrind will process the code based on the selected tool, which will add the instrumentation code to the code and return the code as the final code to the Valgrind core, and finally valgrind the core to run the code.

If you want to check for memory leaks, just add--leak-check=yes to it, and the commands are as follows

Valgrind--tool=memcheck--leak-check=yes ls-l

Code that has been added between tools varies greatly. At the end of each scope, Memcheck adds code to check access and value calculations for each piece of memory, and the code size is increased by at least 12 times times, running at a rate of 25 to 50 times times slower than usual.

Every instruction in the Valgrind emulator executes, so checking tools and profiling tools work not just for your application, but for shared libraries, GNU C libraries, and X's client libraries.

third, start now

First, turn on debug mode when compiling the program (the-G option of the GCC compiler). Without debugging information, even the best valgrind tools will be able to guess which function the particular code belongs to. Turn on the debug option to compile and then use the Valgrind check, Valgrind will give you a detailed report, such as which line of code has a memory leak.

When checking the C + + program, you should also consider another option-fno-inline. It makes the function call chain very clear, which can reduce the confusion of browsing large C + + programs. For example, when using this option, it is easy to check OpenOffice with Memcheck. Of course, you may not be doing this work, but using this option allows Valgrind to generate more accurate error reporting and reduce clutter.

Some compilation optimization options, such as-O2 or higher optimization options, may cause Memcheck to submit incorrect uninitialized reports, so in order to make Valgrind's reports more accurate, it is best not to use optimization options at compile time.

If the program starts with a script, you can modify the code that starts the program in the script, or use the--trace-children=yes option to run the script.

The following is an output report that checks the Ls-l command with Memcheck and executes the following command under the terminal

Valgrind--tool=memcheck Ls-l

The program prints out the results of the ls-l command, and finally the Valgrind inspection report reads as follows:

==4187==

==4187== ERROR summary:0 errors from 0 contexts (suppressed:19 from 2)

==4187== malloc/free:in use at exit:15,154 bytes in blocks.

==4187== malloc/free:310 Allocs, 205 frees, 60,093 bytes.

==4187== for counts of detected errors, rerun with:-V

==4187== searching for pointers to not-freed blocks.

==4187== checked 145,292 bytes.

==4187==

==4187== leak SUMMARY:

==4187== definitely lost:0 bytes in 0 blocks.

==4187== possibly lost:0 bytes in 0 blocks.

==4187== still reachable:15,154 bytes in blocks.

==4187== suppressed:0 bytes in 0 blocks.

==4187== reachable blocks (those to which a pointer is found) are not shown.

==4187== to-them, rerun with:--show-reachable=yes

The "4187" here refers to the process ID of executing ls-l, which facilitates the distinction between reports of different processes. Memcheck will report how much memory is configured and freed, how much memory is leaking, how much memory access is reachable, and how many bytes of memory are checked.

Here are two examples of using Valgrind to do a memory check

Example One (test.c):

#include <string.h>

int main (int argc, char *argv[])
{
    char *ptr;

    ptr = (char*) malloc (a);
    strcpy (PTR, "01234567890");

    return 0;
}

Compiling programs

GCC-G-O test test.c

Execute command with Valgrind

Valgrind--tool=memcheck--leak-check=yes./test

The report reads as follows

==4270== Memcheck, a memory error detector.

==4270== Copyright (C) 2002-2006, and GNU GPL ' d, by Julian Seward et al.

==4270== Using Libvex Rev 1606, a library for dynamic binary translation.

==4270== Copyright (C) 2004-2006, and GNU GPL ' d, by Openworks LLP.

==4270== Using valgrind-3.2.0, a dynamic binary instrumentation framework.

==4270== Copyright (C) 2000-2006, and GNU GPL ' d, by Julian Seward et al.

==4270== for further details, rerun with:-V

==4270==

==4270== Invalid Write of size 1

==4270== at 0x4006190:strcpy (mc_replace_strmem.c:271)

==4270== by 0x80483db:main (Test.c:8)

==4270== address 0x4023032 's 0 bytes after a block of size alloc ' d

==4270== at 0x40044f6:malloc (vg_replace_malloc.c:149)

==4270== by 0x80483c5:main (Test.c:7)

==4270==

==4270== Invalid Write of size 1

==4270== at 0x400619c:strcpy (mc_replace_strmem.c:271)

==4270== by 0x80483db:main (Test.c:8)

==4270== address 0x4023033 's 1 bytes after a block of size alloc ' d

==4270== at 0x40044f6:malloc (vg_replace_malloc.c:149)

==4270== by 0x80483c5:main (Test.c:7)

==4270==

==4270== ERROR Summary:2 errors from 2 contexts (suppressed:12 from 1)

==4270== malloc/free:in use at exit:10 bytes in 1 blocks.

==4270== Malloc/free:1 Allocs, 0 frees, bytes allocated.

==4270== for counts of detected errors, rerun with:-V

==4270== searching for pointers to 1 not-freed blocks.

==4270== checked 51,496 bytes.

==4270==

==4270==

==4270== bytes in 1 blocks are definitely lost-loss record 1 of 1

==4270== at 0x40044f6:malloc (vg_replace_malloc.c:149)

==4270== by 0x80483c5:main (Test.c:7)

==4270==

==4270== leak SUMMARY:

==4270== definitely lost:10 bytes in 1 blocks.

==4270== possibly lost:0 bytes in 0 blocks.

==4270== still reachable:0 bytes in 0 blocks.

==4270== suppressed:0 bytes in 0 blocks.

==4270== reachable blocks (those to which a pointer is found) are not shown.

==4270== to-them, rerun with:--show-reachable=yes

As you can see from this report, the process number is 4270,TEST.C's 8th line of write memory is out of bounds, the strcpy function that causes the write memory to cross the bounds,

Line 7th leaks 10 bytes of memory, causing memory leaks is the malloc function.

Example Two (test2.c)

#include <stdio.h>

int foo (int x)
{
    if (x < 0) {
        printf ("%d", x);
    }

    return 0;
}

int main (int argc, char *argv[])
{
    int x;
   
    Foo (x);

    return 0;
}

Compiling programs

Gcc-g-O test2 test2.c

Using Valgrind to do a memory check

Valgrind--tool=memcheck./test2

The output report is as follows

==4285== Memcheck, a memory error detector.

==4285== Copyright (C) 2002-2006, and GNU GPL ' d, by Julian Seward et al.

==4285== Using Libvex Rev 1606, a library for dynamic binary translation.

==4285== Copyright (C) 2004-2006, and GNU GPL ' d, by Openworks LLP.

==4285== Using valgrind-3.2.0, a dynamic binary instrumentation framework.

==4285== Copyright (C) 2000-2006, and GNU GPL ' d, by Julian Seward et al.

==4285== for further details, rerun with:-V

==4285==

==4285== Conditional Jump or move depends on uninitialised value (s)

==4285== at 0x8048372:foo (test2.c:5)

==4285== by 0x80483b4:main (test2.c:16)

==4285==p P

==4285== ERROR summary:1 errors from 1 contexts (suppressed:12 from 1)

==4285== malloc/free:in use at exit:0 bytes in 0 blocks.

==4285== malloc/free:0 Allocs, 0 frees, 0 bytes allocated.

==4285== for counts of detected errors, rerun with:-V

==4285== all heap blocks were freed-no leaks are.

From this report it can be seen that process PID is the 16th line of the 4285,test2.c file called the Foo function, in the test2.c file, the 5th line foo function uses an uninitialized variable.

Valgrind also has many options for using the Valgrind Man manual page and the online documentation for Valgrind's official website.

Related Article

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.