How to use the Valgrind Memcheck tool for memory leak detection in C + +

Source: Internet
Author: User
Tags valgrind

An important aspect of system programming is to effectively handle memory-related problems. The closer you work to the system, the more memory problems you will have to face. Sometimes these problems are trivial, and more often it becomes a nightmare to debug memory problems. So, in practice, a lot of tools are used to debug memory problems.


Valgrind is a set of simulation-based program debugging and analysis tools running on Linux that contains a kernel-a software-synthesized CPU, and a series of gadgets, each of which can perform a task-debugging, analysis, or testing. Valgrind can detect memory leaks and memory violations, and can analyze the use of the cache, and so on, flexible and powerful, can be straight through the wrong heart, it is the programmer's Swiss Army knife.


The Valgrind Toolkit contains several tools:

  • Memcheck is a memory error detector. It helps to make your programs, especially those written in C and C + +, more accurate.
  • Cachegrind is a cache and branch prediction Analyzer. It helps to make your program run faster.
  • Callgrind is a call graph cache generation parser. It overlaps with the functionality of Cachegrind, but also collects some information that Cachegrind does not collect
  • Helgrind is a thread error detector. It helps to make your multithreaded routines more accurate.
  • DRD is also a thread error detector. It is similar to Helgrind, but uses different analytical techniques, so it is possible to find different problems.
  • Massif is a heap analyzer. It helps to make your program use less memory.
  • Dhat is another different heap parser. It helps to understand the life cycle of blocks, the use of blocks, and the inefficiency of layout.
  • Sgcheck is an experimental tool used to detect the overflow of heaps and global arrays. Its function and Memcheck complement: Sgcheck find problems Memcheck cannot find, and vice versa.
  • BBV is an experimental simpoint basic block vector generator. It is useful for research and development of computer architectures.

Here is a description of how to use the Valgrind Memcheck tool for memory leak detection in C/C + +. The Memcheck tool mainly checks for the following program errors:

    • using uninitialized memory (use of uninitialised memories)
    • Span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:14PX;" > using the freed memory (Reading/writingmemory after it had been free ' d)
    • Use more memory space than malloc allocated (reading/writing off the end of malloc ' d blocks)
    • illegal access to stacks (reading/writinginappropriate areas on the stack)
    • Whether the space requested is free (Memory leaks–where pointers to malloc ' d blocks is lost forever)
    • malloc/free/new/delete application and Release memory matching (mismatched use of malloc/new/new [] vs Free/delete/delete [])
    • SRC and DST overlap (overlapping src and DST pointers in memcpy () and related functions)

The use of these tools is by command: Valgrand--tool=name program name is called separately, when the tool parameter is not specified by default is--tool=memcheck.


before use, you need to ensure that Valgrind is installed:

Use Valgrind Memcheck method:

    • When compiling the code, add the debug parameter-G ( used to generate the line number in the output of the Memcheck, and if an error occurs, you can navigate to where the error occurred )
    • --leak-check=full refers to a full check for memory leaks
    • A.out is an executable program that needs to be checked

1. Using Uninitialized memory
#include <stdio.h> #include <stdlib.h> int main (void) {    char *p;     char c = *p;  Use uninitialized memory     printf ("\ n [%c]\n", c);     return 0;}

In the above code, we try to use the uninitialized pointer "P", let's run Memcheck to check the results:


2. Read/write after memory is freed
#include <stdio.h> #include <stdlib.h> int main (void) {    char *p = malloc (1);    *p = ' a ';     char c = *p;     printf ("\ n [%c]\n", c);     Free (p);    c = *p;//Read/write return 0 after memory is freed        ;}

The debug results are as follows:

3. Read/write from the end of the allocated memory block
#include <stdio.h> #include <stdlib.h> int main (void) {    char *p = malloc (1);    *p = ' a ';     char C = * (p+1); Reads/writes printf from the end of the allocated memory block     ("\ n [%c]\n", c);     Free (p);    return 0;}

The debug results are as follows:

4. Memory Leaks
#include <stdio.h> #include <stdlib.h>//in this code, we requested a byte but did not release it int main (void) {    char *p = malloc (1) ;    *p = ' a ';     char c = *p;     printf ("\ n [%c]\n", c);     return 0;}

The debug results are as follows:

5. Mismatched use of malloc/new/new[] and free/delete/delete[]
#include <stdio.h> #include <stdlib.h> #include <iostream> int main (void) {    char *p = (char*) malloc (1);    *p = ' a ';     char c = *p;     printf ("\ n [%c]\n", c);    Delete p;    return 0;}

in the above code, we used malloc () to allocate memory, but we used the delete operator to remove the memory.
Note : Use g++ to compile the above code, because the delete operator is introduced in C + + and you need to use g++ to compile C + +.

The debug results are as follows:



6. Two-time free memory

#include <stdio.h> #include <stdlib.h> int main (void) {    char *p = (char*) malloc (1);    *p = ' a ';     char c = *p;    printf ("\ n [%c]\n", c);    Free (p);    Free (p);    return 0;}

The debug results are as follows:



This article turns from: Http://www.oschina.net/translate/valgrind-memcheck.


How to use the Valgrind Memcheck tool for memory leak detection in C + +

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.