【2013-12-11】C语言代码检测:valgrind的使用
[历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2013-12-11 标题C语言代码检测valgrind的使用分类编程 / C C 标签CC·valgrind·代码检测C语言代码检测valgrind的使用valgrind的官网地址valgrind的下载和安装valgrind的编译GUI工具valkyrie的编译valgrind的使用备注建立一个简单的被测试文件通过命令行来使用valgrind:通过valkyrie来使用algrind我们做C语言开发时对内存的申请和释放是非常头疼的需要很小心的处理内存。valgrind可以在程序动态执行的时候进行内存检测找出有问题的代码。这里备注下valgrind的使用valgrind的官网地址【 http://valgrind.org/ 】valgrind的下载和安装进入下载页面后可以发现页面上有两个连接可用下载一个是valgrind的源码另一个是valgrind的GUI程序。如下图所示关于valgrind的GUI介绍大家可以参考这个网址【 http://valgrind.org/downloads/guis.html 】里面也介绍了eclipse的插件使用方式。valgrind的编译将两个链接的压缩包下载并解压后进入valgrind3.9的目录可以发现里面有个README里面很详细的介绍了如何编译安装valgrind我截取了部分README的内容如下Building and installing it ~~~~~~~~~~~~~~~~~~~~~~~~~~ Toinstallfrom the Subversion repository:0. Check out the code from SVN, following the instructions at http://www.valgrind.org/downloads/repository.html.1.cdinto thesourcedirectory.2. Run ./autogen.sh to setup the environment(you need the standard autoconf tools todoso).3. Continue with the following instructions... Toinstallfrom a tar.bz2 distribution:4. Run ./configure, with some optionsifyou wish. The only interesting one is the usual--prefix/where/you/want/it/installed.5. Runmake.6. Runmake install, possibly as rootifthe destination permissions require that.7. Seeifit works. Tryvalgrind ls -l.Either this works, or it bombs out with some complaint. In that case, pleaseletus know(see www.valgrind.org). Important!Do not move the valgrind installation into a place different from that specified by--prefixat build time. This will cause things tobreakinsubtle ways, mostly when Valgrind handles fork/exec calls.我们就按照这个指引来安装输入命令make 时间较长./autogen.sh ./configuremakesudomakeinstall然后使用命令检测是否安装成功valgrindls-l成功的话应该有类似下图输出GUI工具valkyrie的编译在valkyrie的目录下有个INSTALL文件里面介绍了如何编译安装valkyrie由于作者本地的QT 环境很乱没有成功也没有深究就直接简单的sudo apt-get install valkyrie 了。大家有兴趣可以自己编译下valkyrie。而且valgrind好像也可以直接apt-get获取作者没有实验。valgrind的使用备注本部分参考【 http://www.ibm.com/developerworks/cn/linux/l-cn-valgrind/ 】【 http://valgrind.org/docs/manual/quick-start.html 】建立一个简单的被测试文件【 sample.c 】#includestdlib.hvoidf(void){int*xmalloc(10*sizeof(int));x[10]0;// problem 1: heap block overrun}// problem 2: memory leak -- x not freedintmain(void){f();return0;}然后在命令行输入gcc-g-O0sample.c-osample通过命令行来使用valgrind:输入命令【 valgrind/sample 】输出如下图所示具体的分析可以参考备注中的链接。通过valkyrie来使用algrind打开valkyrie后点击【 Edit – Options 】点击【 Binary 】选中要测试的可执行文件点击【 OK 】然后点击【 Process – Run 】。会产生分析如下图可以看到使用valkyrie可以看到源码会更方便一点。另外如果使用valkyrie点击【 Help – handbook 】有比较详细的使用说明。