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相关推荐

  1. linux环境下QT程序内存泄露检测-Qt creator +Valgrind检测内存泄漏(linux)

    原文查看具体内容: Qt creator +Valgrind检测内存泄漏(linux)_枫影竹韵的博客-CSDN博客 一.说明 由于Qt creator和valgrind是相互独立的,所以需要安装va ...

  2. valgrind检测内存泄漏,gperftools,memwatch和性能优化Messy_Test

    yum -y install  valgrind 如何在windows使用valgrind_如何在windows下使用f2py_weixin_39621870的博客-CSDN博客 QNX下Valgri ...

  3. 如何在linux下检测内存泄漏

    1.开发背景 在 windows 下使用 VC 编程时,我们通常需要 DEBUG 模式下运行程序,而后调试器将在退出程序时,打印出程序运行过程中在堆上分配而没有释放的内存信息,其中包括代码文件名.行号 ...

  4. Qt Creator使用Memcheck检测内存泄漏

    Qt Creator使用Memcheck检测内存泄漏 使用Memcheck检测内存泄漏 选择内存分析选项 显示可达和间接丢失的块 抑制错误 使用Memcheck检测内存泄漏 您可以使用Valgrind ...

  5. 使用asan检测内存泄漏、堆栈溢出等问题

    一.使用过程 操作过程参考:链接 缘起:程序在移动端崩溃,mac端复现不了,于是在写个崩溃位置函数的调用demo,使用ASAN工具进行排查. 验证过程 1.代码 main.cpp #include & ...

  6. VC使用CRT调试功能检测内存泄漏(转载)

    /*********************************************************************************** 检测内存泄漏的基本工具是调试器 ...

  7. vs2008 使用Visual Leak Detector检测内存泄漏

    http://hi.baidu.com/maydaygmail/item/8ea6ebef87ca9103560f1dfe 转自:http://hi.baidu.com/sunchongjing/bl ...

  8. Linux下如何发现内存泄漏问题(测试角度)

    目录 一.内存泄漏的概念 二.测试方法 1.长期稳定性测试 2.大数据量测试 3.结合free.top等命令进行资源监控 4.持续观察上层应用运行情况 5.查看日志 6.检查代码 一.内存泄漏的概念 ...

  9. unity如何检测内存泄漏_如何排查Java内存泄漏?看懂这一篇就够用了

    原文:https://www.toptal.com/java/hunting-memory-leaks-in-java 作者:Jose Ferreirade Souza Filho 译者:Emma来源 ...

最新文章

  1. 预训练时代微调新范式,高性能加速2800%,NLPer赶紧看过来!
  2. 豆瓣评分 9.3,史上最好的 C 语言著作,竟然翻车了......
  3. kafka身份认证 maxwell_聊聊MaxwellKafkaProducer
  4. 内核地址空间和用户地址空间
  5. 【渝粤题库】陕西师范大学200131中国古代文论 作业(专升本)
  6. MySql某一列累计查询
  7. DOM查找元素的方法总结
  8. C语言 二维数组定义和使用 - C语言零基础入门教程
  9. html 不显示null,如果model.entity为null,则不显示/写特定的html
  10. 如何解除FSO上传程序小于200k限制?
  11. 一、bootstrap table 初体验
  12. 如何重启 Windows 10 子系统(WSL) ubuntu
  13. 面试官的窒息逼问:2021最全的接口测试面试题及参考答案
  14. 北理计算机2017,←2017 计算机学院 2019→
  15. USB免驱接触式FM4442卡ISO7816读写器S3-BMU-A0函数使用规则
  16. 计算机网络的应用领域有那些,计算机网络应用领域
  17. CentOS Install Passenger for ROR
  18. 思考“手绘家谱”的算法
  19. Kibana【从无到有从有到无】【搜索引擎】【K4】可视化
  20. 2019 11 14

热门文章

  1. uboot启动流程概述_关于RISCV启动部分的思考~
  2. 本月 上月 php,显示本月,上月,今天,今年以及各时间起点与
  3. c++调用python操作mongo
  4. Pytorch搭建Faster R-CNN目标检测平台
  5. Vue.js 动态组件 异步组件
  6. git部署与基本命令汇总
  7. 概率统计:第八章:假设检验
  8. 数据库SQL面试题七则
  9. 【python图像处理】图像的读取、显示与保存
  10. 重温Android四大组件(一)—Activity的生命周期