Memory leaks # # # valgrind # valgrind use

Usage: valgrind [options] prog-and-args [options]: Common options for all Valgrind tool

  1. -tool = <name> The most common options. Toolname run valgrind tool named. Default memcheck.

  2. h -help display help information.

  3. -version valgrind show version of the kernel, each tool has its own version.

  4. q quiet operation -quiet, print only error messages.

  5. v -verbose more detailed information, increasing the number of statistical error.

  6. -trace-children = no |? yes tracking child thread [no]

  7. -track-fds = no | yes tracks open file description? [No]

  8. -time-stamp = no | yes LOG to increase the time stamp information [no]?

  9. -log-fd = <number> to the output descriptor file LOG [2 = stderr]

  10. -log-file = <file> output information written to the file filename.PID, PID is the ID is to run the program

  11. -log-file-exactly = <file> output information to the file LOG

  12. -log-file-qualifier = <VAR> get the value of the environment variable to do is name the output file information. [None]

  13. -log-socket = ipaddr: port to the LOG output socket, ipaddr: port

LOG information output

  1. -xml = yes output information in xml format, is available only memcheck

  2. -num-callers=<number> show <number> callers in stack traces [12]

  3. -error-limit = no | yes If too many errors, it stops displaying new error [yes]?

  4. -error-exitcode = <number> If errors are found error code is returned [0 = disable]

  5. -db-attach = no | yes When an error occurs, valgrind gdb debugger will start automatically. [No]

  6. -db-command = <command> start the debugger command line options [gdb -nw% f% p]

Memcheck tools applicable to the relevant options:

  1. -leak-check = no | summary | full requirements of the leak to give detailed information [summary]?

  2. -leak-resolution=low|med|high how much bt merging in leak check [low]

  3. -show-reachable=no|yes show reachable blocks in leak check? [no]

Valgrind Application Example (a)

Here is a problematic C code test.c

#i nclude <stdlib.h>
void f(void)
{
   int* x = malloc(10 * sizeof(int));
   x[10] = 0;  //问题1: 数组下标越界
}                  //问题2: 内存没有释放

 

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

 

1、 编译程序test.c
gcc -Wall test.c -g -o test
2、 使用Valgrind检查程序BUG
valgrind --tool=memcheck --leak-check=full ./test
3、 分析输出的调试信息
==3908== Memcheck, a memory error detector.
==3908== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==3908== Using LibVEX rev 1732, a library for dynamic binary translation.
==3908== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==3908== Using valgrind-3.2.3, a dynamic binary instrumentation framework.
==3908== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==3908== For more details, rerun with: -v
==3908== 
--3908-- DWARF2 CFI reader: unhandled CFI instruction 0:50
--3908-- DWARF2 CFI reader: unhandled CFI instruction 0:50
/*数组越界错误*/
==3908== Invalid write of size 4      
==3908==    at 0x8048384: f (test.c:6)
==3908==    by 0x80483AC: main (test.c:11)
==3908==  Address 0x400C050 is 0 bytes after a block of size 40 alloc'd
==3908==    at 0x40046F2: malloc (vg_replace_malloc.c:149)
==3908==    by 0x8048377: f (test.c:5)
==3908==    by 0x80483AC: main (test.c:11)
==3908== 
==3908== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 14 from 1)
==3908== malloc/free: in use at exit: 40 bytes in 1 blocks. 
==3908== malloc/free: 1 allocs, 0 frees, 40 bytes allocated.
==3908== For counts of detected errors, rerun with: -v
==3908== searching for pointers to 1 not-freed blocks.
==3908== checked 59,124 bytes.
==3908== 
==3908== 
/*有内存空间没有释放*/
==3908== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3908==    at 0x40046F2: malloc (vg_replace_malloc.c:149)
==3908==    by 0x8048377: f (test.c:5)
==3908==    by 0x80483AC: main (test.c:11)
==3908== 
==3908== LEAK SUMMARY:
==3908==    definitely lost: 40 bytes in 1 blocks.
==3908==      possibly lost: 0 bytes in 0 blocks.
==3908==    still reachable: 0 bytes in 0 blocks.
==3908==         suppressed: 0 bytes in 0 blocks.

 

 

 

Valgrind 使用举例(二)

 

 

 

没有内存泄漏
编译C++ -“Hello kiccleaf!”

 

#include <iostream.h>

 

int main()
{
 cout << "Hello kiccleaf!/n" << endl;
 return 0;
}

 

用g++编译C++程序
g++ Hello.cpp -o hello

 

 

 

[root@xuanAS4 LNMP]# valgrind --tool=memcheck --leak-check=full ./hello
==8926== Memcheck, a memory error detector.
==8926== Copyright (C) 2002-2008, and GNU GPL'd, by Julian Seward et al.
==8926== Using LibVEX rev 1884, a library for dynamic binary translation.
==8926== Copyright (C) 2004-2008, and GNU GPL'd, by OpenWorks LLP.
==8926== Using valgrind-3.4.1, a dynamic binary instrumentation framework.
==8926== Copyright (C) 2000-2008, and GNU GPL'd, by Julian Seward et al.
==8926== For more details, rerun with: -v
==8926== 
Hello kiccleaf!

 

==8926== 
==8926== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 1)
==8926== malloc/free: in use at exit: 0 bytes in 0 blocks.
==8926== malloc/free: 0 allocs, 0 frees, 0 bytes allocated.
==8926== For counts of detected errors, rerun with: -v
==8926== All heap blocks were freed -- no leaks are possible

Memcheck found using the common memory problems

Problems when developing applications, most commonly encountered Linux platform is the wrong use of memory, we summarize common usage of memory errors, and explains how to use valgrind will detect it.

The use of uninitialized memory

problem analysis:

For variables located in different segments of the program, its initial value is different, the global and static variables initial value of 0, and the variable local variables and dynamic applications, the initial value is a random value. If the program uses a random variable value, then the behavior of the program becomes unpredictable.

The following program is a common use case of uninitialized variables. Array is a local variable whose initial value is a random value, and not during initialization to initialize all the array members, so when the array to be used next potential has a memory problem.

Listing 3

Result analysis:

Assuming that this file is named: badloop.c , the resulting executable program is badloop . Subjected to testing memcheck, the output follows.

Listing 4

Output shows, at line 11 in the program, the program jumps depends on an uninitialized variable. Accurately find the above-mentioned problems in the program.

Bounds memory read and write

problem analysis:

This situation means: You should not visit / do not have permission to access a memory address space, such as cross-border access the array; for dynamic memory access beyond the scope of application memory size. The following program is a typical array of cross-border issues. pt is a local variable array, its size is 4, p pt initially points to the starting address of the array, but after p cycles superimposed, p pt beyond the scope of the array, then at this time if a write operation to be p, the consequences the unpredictable.

Listing 5

Result analysis:

Assuming that the executable file named badacc.cpp, generated for badacc, test it with memcheck, the output follows.

Dump failed to re-upload canceledListing 6 

The results show that the output at line 15 of the program, illegal write operation performed; in line 16, the read operation performed illegal. Accurately find the above problems.

Memory cover

problem analysis:

C language powerful and scary is that it can directly manipulate memory, C standard library provides a large number of such functions, such as strcpy, strncpy, memcpy, strcat, etc. These functions have a common characteristic is the need to set the source address (src ), and the destination address (dst), src and dst address pointed to overlap can not occur, otherwise the results will be unpredictable.

The following is an example of a src and dst overlap occurs. 15 and line 17, src and dst address difference of 20 points, but a copy of the specified length is 21, this value will be copied and before the cover. Line 24 similar procedures, src (x + 20) and dst (X) address pointed to by a difference of 20, but has a length of 21 dst, covering this memory also occur.

Listing 7

Result analysis:

Assuming that the executable file named badlap.cpp, generated for badlap, test it with memcheck, the output follows.

Click to enlarge

The output of the program displays the lines 15,17,24, the source address and destination address to overlap. And accurately find the above-mentioned problems.

Dynamic memory management errors

problem analysis:

Common memory allocation in three ways: static memory allocation on the stack, allocated on the heap. Global variables are static storage, they are at compile time is allocated storage space, local variables within the function belongs to allocate on the stack, and the most flexible use of memory allocated on the heap undoubtedly, also known as dynamic allocation of memory. Dynamic memory allocation function used include: malloc, alloc, realloc, new like, comprising a dynamic release function free, delete.

Once you have successfully applied for a dynamic memory, we need its own memory management, which in turn is most likely to make mistakes. The following section of the program, including a dynamic memory management of common mistakes.

Listing 9

Common dynamic memory management errors include:

  1.  
    • Inconsistent application and release

Because C ++ is compatible with C, and C and C ++ memory application and release functions are different, so in a C ++ program, there are two sets of dynamic memory management functions. The same rule is to use a memory C would apply for release in C mode; memory mode application in C ++, with the release of C ++ way. That is, memory use malloc / alloc / realloc apply for the release of a free; delete memory with the release of a new way of application. In the program, but the application memory using malloc with delete to free manner, although this is not a problem in many cases, but this is definitely a potential problem.

  1.  
    • Application and release do not match

Application how much memory, how much will release when finished. If there is no release, or less freed is the memory leak; multi-released also cause problems. The above procedure, the pointer p and pt points to the same piece of memory, has been released twice.

  1.  
    • After the release of still read and write

Essentially, the system will maintain a dynamic memory on the heap lists, if released, it means that the memory block can continue to be allocated to other parts, if memory is freed after the visit, it is possible to cover the rest of the information, which is a serious error, line 16 of the above program would still write this memory after release.

Result analysis:

Assuming that the executable file named badmac.cpp, generated for badmac, test it with memcheck, the output follows.
Listing 10

Output display, and inconsistent dispensing line 14 is released function; 16 illegal write line, i.e. to release the write memory address value; line 17 to release the memory function is invalid. Accurately identify the three above-mentioned problems.

Memory leak

Problem Description:

Memory leaks (Memory leak) means that dynamic memory in a program application, in neither release after use, they can not access the rest of the program. Memory leak in the development of large programs in the most headaches, so it was said, memory leaks can not be avoided. In actual fact, prevent memory leaks from good programming practice to start, another important point is to strengthen the unit testing (Unit Test), and memcheck is such a great tool.

Here is a typical memory leak case. mk main function calls the function spanning tree nodes, but after the call is complete, but there is no corresponding function: nodefr release memory, so the memory of this tree can not be accessed by other parts, resulting in a memory leak.

In a separate function, each person's sense of memory leaks are relatively strong. But in many cases, we will do to malloc / free or new / delete some packaging to meet our specific needs, you can not do both in the use and release of a function. This example also illustrates the local memory leak most likely to occur: that is, the interface of the two portions, and a function for the memory, a function to release memory. And these functions are developed by different people use, so the possibility of memory leaks caused by relatively big. This unit tests need to develop good habits, eliminate memory leaks in the initial stage.

Listing 1 

Listing 11.2 


Listing 11.3

Result analysis:

Assuming that the above file fame tree.h, tree.cpp, badleak.cpp, the resulting executable program for badleak, with memcheck be tested, the following output.



Click to enlarge

This sample program is a tree generation process, the size of each tree node is 12 (considering the memory alignment), a total of eight nodes. As can be seen from the output, all memory leaks were found. Memcheck memory leaks into two, one is possible memory leaks (Possibly lost), another memory leak is determined (Definitely lost). Possibly lost means that there is still a pointer to access a block of memory, but the pointer is not the first memory address. Definitely lost means no longer able to access this memory. Definitely lost and is divided into two types: direct (direct) and indirect (indirect). Direct and indirect difference is that there is no direct pointer to the memory, indirect pointer is pointing to the memory located at the memory leak. In the above example, the root node is directly lost, while the other nodes are indirectly lost.

Published 170 original articles · won praise 207 · Views 4.59 million +

Guess you like

Origin blog.csdn.net/xiaoting451292510/article/details/104943986