0.前言
内存泄漏是c++程序常见的问题了,特别是服务类程序,当系统模块过多或者逻辑复杂后,很难通过代码看出内存泄漏;
valgrind是一个开源的,检测c++程序内存泄漏有效工具,编译时加上-g选项可以定位到代码行,同时还检查‘野指针’,检查malloc与free是否匹配等功能;
下载源码安装这里就不重复写了,下面通过一个简单的程序记录valgrind的用法。
1.示例代码
main.c
- //main.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- printf("start init\n");
- char *p = (char *)malloc(1024);
- char *ptr;
- if(ptr)
- {
- printf("ptr:%p\n", ptr);
- }
- getchar();
- return 0;
- }
2.编译命令
makefile
- #makefile
- main:main.o
- g++ -g3 main.c -o main
- clean:
- rm -f main.o
- rm -f main
3.调试命令
debug.sh
- #!/bin/bash
- #debug.sh
- valgrind -v --log-file=valgrind.log --tool=memcheck --leak-check=full --show-mismatched-frees=yes main
4.日志输出
cat valgrind.log
- ==2211== Memcheck, a memory error detector
- ==2211== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
- ==2211== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
- ==2211== Command: main
- ==2211== Parent PID: 2210
- ==2211==
- --2211--
- --2211-- Valgrind options:
- --2211-- -v
- --2211-- --log-file=valgrind.log
- --2211-- --tool=memcheck
- --2211-- --leak-check=full
- --2211-- --show-mismatched-frees=yes
- --2211-- Contents of /proc/version:
- --2211-- Linux version 4.4.0-98-generic (buildd@lcy01-03) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4) ) #121-Ubuntu SMP Tue Oct 10 14:24:03 UTC 2017
- --2211--
- --2211-- Arch and hwcaps: AMD64, LittleEndian, amd64-cx16-lzcnt-rdtscp-sse3-avx-avx2-bmi
- --2211-- Page sizes: currently 4096, max supported 4096
- --2211-- Valgrind library directory: /usr/local/lib/valgrind
- --2211-- Reading syms from /home/lsx/testspace/valgrind/main
- --2211-- Reading syms from /lib/x86_64-linux-gnu/ld-2.23.so
- --2211-- Considering /lib/x86_64-linux-gnu/ld-2.23.so ..
- --2211-- .. CRC mismatch (computed 10768843 wanted ef0d0121)
- --2211-- Considering /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.23.so ..
- --2211-- .. CRC is valid
- --2211-- Reading syms from /usr/local/lib/valgrind/memcheck-amd64-linux
- --2211-- object doesn't have a dynamic symbol table
- --2211-- Scheduler: using generic scheduler lock implementation.
- --2211-- Reading suppressions file: /usr/local/lib/valgrind/default.supp
- ==2211== embedded gdbserver: reading from /tmp/vgdb-pipe-from-vgdb-to-2211-by-lsx-on-???
- ==2211== embedded gdbserver: writing to /tmp/vgdb-pipe-to-vgdb-from-2211-by-lsx-on-???
- ==2211== embedded gdbserver: shared mem /tmp/vgdb-pipe-shared-mem-vgdb-2211-by-lsx-on-???
- ==2211==
- ==2211== TO CONTROL THIS PROCESS USING vgdb (which you probably
- ==2211== don't want to do, unless you know exactly what you're doing,
- ==2211== or are doing some strange experiment):
- ==2211== /usr/local/lib/valgrind/../../bin/vgdb --pid=2211 ...command...
- ==2211==
- ==2211== TO DEBUG THIS PROCESS USING GDB: start GDB like this
- ==2211== /path/to/gdb main
- ==2211== and then give GDB the following command
- ==2211== target remote | /usr/local/lib/valgrind/../../bin/vgdb --pid=2211
- ==2211== --pid is optional if only one valgrind process is running
- ==2211==
- --2211-- REDIR: 0x401cdc0 (ld-linux-x86-64.so.2:strlen) redirected to 0x380a0df1 (vgPlain_amd64_linux_REDIR_FOR_strlen)
- --2211-- REDIR: 0x401b710 (ld-linux-x86-64.so.2:index) redirected to 0x380a0e0b (vgPlain_amd64_linux_REDIR_FOR_index)
- --2211-- Reading syms from /usr/local/lib/valgrind/vgpreload_core-amd64-linux.so
- --2211-- Reading syms from /usr/local/lib/valgrind/vgpreload_memcheck-amd64-linux.so
- ==2211== WARNING: new redirection conflicts with existing -- ignoring it
- --2211-- old: 0x0401cdc0 (strlen ) R-> (0000.0) 0x380a0df1 vgPlain_amd64_linux_REDIR_FOR_strlen
- --2211-- new: 0x0401cdc0 (strlen ) R-> (2007.0) 0x04c30a90 strlen
- --2211-- REDIR: 0x401b930 (ld-linux-x86-64.so.2:strcmp) redirected to 0x4c31b40 (strcmp)
- --2211-- REDIR: 0x401db20 (ld-linux-x86-64.so.2:mempcpy) redirected to 0x4c34d20 (mempcpy)
- --2211-- Reading syms from /lib/x86_64-linux-gnu/libc-2.23.so
- --2211-- Considering /lib/x86_64-linux-gnu/libc-2.23.so ..
- --2211-- .. CRC mismatch (computed f3344b67 wanted 8e4ae80b)
- --2211-- Considering /usr/lib/debug/lib/x86_64-linux-gnu/libc-2.23.so ..
- --2211-- .. CRC is valid
- --2211-- REDIR: 0x4ec7e50 (libc.so.6:strcasecmp) redirected to 0x4a28770 (_vgnU_ifunc_wrapper)
- --2211-- REDIR: 0x4ec36d0 (libc.so.6:strcspn) redirected to 0x4a28770 (_vgnU_ifunc_wrapper)
- --2211-- REDIR: 0x4eca140 (libc.so.6:strncasecmp) redirected to 0x4a28770 (_vgnU_ifunc_wrapper)
- --2211-- REDIR: 0x4ec5b40 (libc.so.6:strpbrk) redirected to 0x4a28770 (_vgnU_ifunc_wrapper)
- --2211-- REDIR: 0x4ec5ed0 (libc.so.6:strspn) redirected to 0x4a28770 (_vgnU_ifunc_wrapper)
- --2211-- REDIR: 0x4ec759b (libc.so.6:memcpy@GLIBC_2.2.5) redirected to 0x4a28770 (_vgnU_ifunc_wrapper)
- --2211-- REDIR: 0x4ec5850 (libc.so.6:rindex) redirected to 0x4c30410 (rindex)
- --2211-- REDIR: 0x4ec3b70 (libc.so.6:strlen) redirected to 0x4c309d0 (strlen)
- --2211-- REDIR: 0x4ebc580 (libc.so.6:malloc) redirected to 0x4c2db2f (malloc)
- ==2211== Conditional jump or move depends on uninitialised value(s)
- ==2211== at 0x40062B: main (main.c:10)
- ==2211==
- --2211-- REDIR: 0x4ebc940 (libc.so.6:free) redirected to 0x4c2ec29 (free)
- ==2211==
- ==2211== HEAP SUMMARY:
- ==2211== in use at exit: 1,024 bytes in 1 blocks
- ==2211== total heap usage: 3 allocs, 2 frees, 3,072 bytes allocated
- ==2211==
- ==2211== Searching for pointers to 1 not-freed blocks
- ==2211== Checked 69,384 bytes
- ==2211==
- ==2211== 1,024 bytes in 1 blocks are definitely lost in loss record 1 of 1
- ==2211== at 0x4C2DBB6: malloc (vg_replace_malloc.c:299)
- ==2211== by 0x400621: main (main.c:8)
- ==2211==
- ==2211== LEAK SUMMARY:
- ==2211== definitely lost: 1,024 bytes in 1 blocks
- ==2211== indirectly lost: 0 bytes in 0 blocks
- ==2211== possibly lost: 0 bytes in 0 blocks
- ==2211== still reachable: 0 bytes in 0 blocks
- ==2211== suppressed: 0 bytes in 0 blocks
- ==2211==
- ==2211== Use --track-origins=yes to see where uninitialised values come from
- ==2211== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
- ==2211==
- ==2211== 1 errors in context 1 of 2:
- ==2211== Conditional jump or move depends on uninitialised value(s)
- ==2211== at 0x40062B: main (main.c:10)
- ==2211==
- ==2211== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
5.其他选项
valgrind --help
- usage: valgrind [options] prog-and-args
- tool-selection option, with default in [ ]:
- --tool=<name> use the Valgrind tool named <name> [memcheck]
- basic user options for all Valgrind tools, with defaults in [ ]:
- -h --help show this message
- --help-debug show this message, plus debugging options
- --version show version
- -q --quiet run silently; only print error msgs
- -v --verbose be more verbose -- show misc extra info
- --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]
- --trace-children-skip=patt1,patt2,... specifies a list of executables
- that --trace-children=yes should not trace into
- --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=
- but check the argv[] entries for children, rather
- than the exe name, to make a follow/no-follow decision
- --child-silent-after-fork=no|yes omit child output between fork & exec? [no]
- --vgdb=no|yes|full activate gdbserver? [yes]
- full is slower but provides precise watchpoint/step
- --vgdb-error=<number> invoke gdbserver after <number> errors [999999999]
- to get started quickly, use --vgdb-error=0
- and follow the on-screen directions
- --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]
- where event is one of:
- startup exit valgrindabexit all none
- --track-fds=no|yes track open file descriptors? [no]
- --time-stamp=no|yes add timestamps to log messages? [no]
- --log-fd=<number> log messages to file descriptor [2=stderr]
- --log-file=<file> log messages to <file>
- --log-socket=ipaddr:port log messages to socket ipaddr:port
- user options for Valgrind tools that report errors:
- --xml=yes emit error output in XML (some tools only)
- --xml-fd=<number> XML output to file descriptor
- --xml-file=<file> XML output to <file>
- --xml-socket=ipaddr:port XML output to socket ipaddr:port
- --xml-user-comment=STR copy STR verbatim into XML output
- --demangle=no|yes automatically demangle C++ names? [yes]
- --num-callers=<number> show <number> callers in stack traces [12]
- --error-limit=no|yes stop showing new errors if too many? [yes]
- --error-exitcode=<number> exit code to return if errors found [0=disable]
- --error-markers=<begin>,<end> add lines with begin/end markers before/after
- each error output in plain text mode [none]
- --show-below-main=no|yes continue stack traces below main() [no]
- --default-suppressions=yes|no
- load default suppressions [yes]
- --suppressions=<filename> suppress errors described in <filename>
- --gen-suppressions=no|yes|all print suppressions for errors? [no]
- --input-fd=<number> file descriptor for input [0=stdin]
- --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [yes]
- --max-stackframe=<number> assume stack switch for SP changes larger
- than <number> bytes [2000000]
- --main-stacksize=<number> set size of main thread's stack (in bytes)
- [min(max(current 'ulimit' value,1MB),16MB)]
- user options for Valgrind tools that replace malloc:
- --alignment=<number> set minimum alignment of heap allocations [16]
- --redzone-size=<number> set minimum size of redzones added before/after
- heap blocks (in bytes). [16]
- uncommon user options for all Valgrind tools:
- --fullpath-after= (with nothing after the '=')
- show full source paths in call stacks
- --fullpath-after=string like --fullpath-after=, but only show the
- part of the path after 'string'. Allows removal
- of path prefixes. Use this flag multiple times
- to specify a set of prefixes to remove.
- --extra-debuginfo-path=path absolute path to search for additional
- debug symbols, in addition to existing default
- well known search paths.
- --debuginfo-server=ipaddr:port also query this server
- (valgrind-di-server) for debug symbols
- --allow-mismatched-debuginfo=no|yes [no]
- for the above two flags only, accept debuginfo
- objects that don't "match" the main object
- --smc-check=none|stack|all|all-non-file [all-non-file]
- checks for self-modifying code: none, only for
- code found in stacks, for all code, or for all
- code except that from file-backed mappings
- --read-inline-info=yes|no read debug info about inlined function calls
- and use it to do better stack traces. [yes]
- on Linux/Android/Solaris for Memcheck/Helgrind/DRD
- only. [no] for all other tools and platforms.
- --read-var-info=yes|no read debug info on stack and global variables
- and use it to print better error messages in
- tools that make use of it (Memcheck, Helgrind,
- DRD) [no]
- --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [5000]
- --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]
- --vgdb-prefix=<prefix> prefix for vgdb FIFOs [/tmp/vgdb-pipe]
- --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]
- --run-cxx-freeres=no|yes free up libstdc++ memory at exit on Linux
- and Solaris? [yes]
- --sim-hints=hint1,hint2,... activate unusual sim behaviours [none]
- where hint is one of:
- lax-ioctls lax-doors fuse-compatible enable-outer
- no-inner-prefix no-nptl-pthread-stackcache none
- --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]
- --kernel-variant=variant1,variant2,...
- handle non-standard kernel variants [none]
- where variant is one of:
- bproc android-no-hw-tls
- android-gpu-sgx5xx android-gpu-adreno3xx none
- --merge-recursive-frames=<number> merge frames between identical
- program counters in max <number> frames) [0]
- --num-transtab-sectors=<number> size of translated code cache [16]
- more sectors may increase performance, but use more memory.
- --avg-transtab-entry-size=<number> avg size in bytes of a translated
- basic block [0, meaning use tool provided default]
- --aspace-minaddr=0xPP avoid mapping memory below 0xPP [guessed]
- --valgrind-stacksize=<number> size of valgrind (host) thread's stack
- (in bytes) [1048576]
- --show-emwarns=no|yes show warnings about emulation limits? [no]
- --require-text-symbol=:sonamepattern:symbolpattern abort run if the
- stated shared object doesn't have the stated
- text symbol. Patterns can contain ? and *.
- --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname
- specify patterns for function wrapping or replacement.
- To use a non-libc malloc library that is
- in the main exe: --soname-synonyms=somalloc=NONE
- in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so
- --sigill-diagnostics=yes|no warn about illegal instructions? [yes]
- --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer
- than <number> good frames found [0, meaning "disabled"]
- NOTE: stack scanning is only available on arm-linux.
- --unw-stack-scan-frames=<number> Max number of frames that can be
- recovered by stack scanning [5]
- --resync-filter=no|yes|verbose [yes on MacOS, no on other OSes]
- attempt to avoid expensive address-space-resync operations
- --max-threads=<number> maximum number of threads that valgrind can
- handle [500]
- user options for Memcheck:
- --leak-check=no|summary|full search for memory leaks at exit? [summary]
- --leak-resolution=low|med|high differentiation of leak stack traces [high]
- --show-leak-kinds=kind1,kind2,.. which leak kinds to show?
- [definite,possible]
- --errors-for-leak-kinds=kind1,kind2,.. which leak kinds are errors?
- [definite,possible]
- where kind is one of:
- definite indirect possible reachable all none
- --leak-check-heuristics=heur1,heur2,... which heuristics to use for
- improving leak search false positive [all]
- where heur is one of:
- stdstring length64 newarray multipleinheritance all none
- --show-reachable=yes same as --show-leak-kinds=all
- --show-reachable=no --show-possibly-lost=yes
- same as --show-leak-kinds=definite,possible
- --show-reachable=no --show-possibly-lost=no
- same as --show-leak-kinds=definite
- --undef-value-errors=no|yes check for undefined value errors [yes]
- --track-origins=no|yes show origins of undefined values? [no]
- --partial-loads-ok=no|yes too hard to explain here; see manual [yes]
- --expensive-definedness-checks=no|yes
- Use extra-precise definedness tracking [no]
- --freelist-vol=<number> volume of freed blocks queue [20000000]
- --freelist-big-blocks=<number> releases first blocks with size>= [1000000]
- --workaround-gcc296-bugs=no|yes self explanatory [no]. Deprecated.
- Use --ignore-range-below-sp instead.
- --ignore-ranges=0xPP-0xQQ[,0xRR-0xSS] assume given addresses are OK
- --ignore-range-below-sp=<number>-<number> do not report errors for
- accesses at the given offsets below SP
- --malloc-fill=<hexnumber> fill malloc'd areas with given value
- --free-fill=<hexnumber> fill free'd areas with given value
- --keep-stacktraces=alloc|free|alloc-and-free|alloc-then-free|none
- stack trace(s) to keep for malloc'd/free'd areas [alloc-and-free]
- --show-mismatched-frees=no|yes show frees that don't match the allocator? [yes]
- Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc
- Memcheck is Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
- Valgrind is Copyright (C) 2000-2015, and GNU GPL'd, by Julian Seward et al.
- LibVEX is Copyright (C) 2004-2015, and GNU GPL'd, by OpenWorks LLP et al.
- Bug reports, feedback, admiration, abuse, etc, to: www.valgrind.org.
6.参考资料
https://www.cnblogs.com/nicebear/archive/2012/05/05/2485054.html
https://www.cnblogs.com/wangkangluo1/archive/2011/07/20/2111248.html
http://blog.csdn.net/miss_acha/article/details/19839715
http://blog.csdn.net/strategycn/article/details/7865525
https://www.cnblogs.com/lanxuezaipiao/p/3604533.html
http://blog.csdn.net/jinzeyu_cn/article/details/45969877
转自: http://blog.csdn.net/shixin_0125/article/details/78590796