日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux工具之检测内存泄漏-valgrind

發布時間:2025/3/21 linux 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux工具之检测内存泄漏-valgrind 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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.og++ -g3 main.c -o main clean:rm -f main.orm -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-argstool-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 executablesthat --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, ratherthan 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=0and 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:portuser 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/aftereach error output in plain text mode [none]--show-below-main=no|yes continue stack traces below main() [no]--default-suppressions=yes|noload 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 largerthan <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/afterheap 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 thepart of the path after 'string'. Allows removalof path prefixes. Use this flag multiple timesto specify a set of prefixes to remove.--extra-debuginfo-path=path absolute path to search for additionaldebug symbols, in addition to existing defaultwell 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 debuginfoobjects 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 forcode found in stacks, for all code, or for allcode except that from file-backed mappings--read-inline-info=yes|no read debug info about inlined function callsand use it to do better stack traces. [yes]on Linux/Android/Solaris for Memcheck/Helgrind/DRDonly. [no] for all other tools and platforms.--read-var-info=yes|no read debug info on stack and global variablesand use it to print better error messages intools 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 Linuxand Solaris? [yes]--sim-hints=hint1,hint2,... activate unusual sim behaviours [none] where hint is one of:lax-ioctls lax-doors fuse-compatible enable-outerno-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-tlsandroid-gpu-sgx5xx android-gpu-adreno3xx none--merge-recursive-frames=<number> merge frames between identicalprogram 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 translatedbasic 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 thestated shared object doesn't have the statedtext symbol. Patterns can contain ? and *.--soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym sonamespecify patterns for function wrapping or replacement.To use a non-libc malloc library that isin the main exe: --soname-synonyms=somalloc=NONEin 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 fewerthan <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 berecovered 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 canhandle [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 forimproving 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=yessame as --show-leak-kinds=definite,possible--show-reachable=no --show-possibly-lost=nosame 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|yesUse 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 foraccesses 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|nonestack 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, ./.valgrindrcMemcheck 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

總結

以上是生活随笔為你收集整理的linux工具之检测内存泄漏-valgrind的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。