valgrind基本使用
1。valgrind是一个内存检测工具,类似的还有purify,insure++等
2。测试文件test.c
test.c :
main(){
int* a=new int[100];
return 0;
}
第一步:gcc -o test test.c
第二步: valgrind --tool=memcheck --leak-check=yes ./test
结果:
==3053== Memcheck, a memory error detector
==3053== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==3053== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==3053== Command: ./a.out
==3053==
==3053==
==3053== HEAP SUMMARY:
==3053== in use at exit: 400 bytes in 1 blocks
==3053== total heap usage: 1 allocs, 0 frees, 400 bytes allocated
==3053==
==3053== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3053== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3053== by 0x8048528: main (temp.cc:41)
==3053==
==3053== LEAK SUMMARY:
==3053== definitely lost: 400 bytes in 1 blocks
==3053== indirectly lost: 0 bytes in 0 blocks
==3053== possibly lost: 0 bytes in 0 blocks
==3053== still reachable: 0 bytes in 0 blocks
==3053== suppressed: 0 bytes in 0 blocks
==3053==
==3053== For counts of detected and suppressed errors, rerun with: -v
==3053== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
分析:
上面的==3053==,3053代表test的进程号
从上面可看到 ,by 0x8048528:main(temp.cc:41)第41行用operator new分配了400字节内存但是没有释放,最后总结此进程泄露内存400字节
3.将内存检测工具与gdb一起使用
命令: valgrind --tool=memcheck --leak-check=yes --db-attach=yes ./test
--db-attach默认调试器是GDB,可以使用--db-attach=<command>指定
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2012-06-22 [转]不要把大脑当做磁盘