2026/1/18 22:59:06
网站建设
项目流程
福州 网站建设 快搜网络,全国学校信息查询官网,建设银行客户端官方网站,动漫制作技术专升本对口专业1.Valgrind 的核心组件#xff08;工具集#xff09;memcheck 内存泄漏、内存错误检测#xff08;越界 / 野指针 / 双重释放#xff09;cachegrind 缓存命中率#xff0c;cpu性能分析callgrind 函数调用关系、执行次数、耗时分析helgrind 线程竞争、死锁检测massif 堆内存…1.Valgrind 的核心组件工具集memcheck 内存泄漏、内存错误检测越界 / 野指针 / 双重释放cachegrind 缓存命中率cpu性能分析callgrind 函数调用关系、执行次数、耗时分析helgrind 线程竞争、死锁检测massif 堆内存使用趋势分析其中mencheck是最常用的也是本文讲解的核心用法格式valgrind[通用参数]--toolmemcheck[memcheck参数]程序名[程序参数]基础命令valgrind --toolmemcheck\--leak-checkfull\# 详细检测所有内存泄漏--show-leak-kindsall\# 显示所有泄漏类型确定/间接/可能--track-originsyes\# 定位内存越界/野指针的根源精准但稍慢--verbose\# 输出额外调试信息--log-filevalgrind.log\# 文本日志输出到文件--xmlyes\# 启用 XML 格式输出--xml-filevalgrind.xml\# XML 若使用xml日志输出到文件必须补充./test# 待检测的程序可加参数如 ./test 123参数– show-leak-kindsall 显示 4 种泄漏类型definitely lost明确泄漏必须修复indirectly lost间接泄漏如容器内对象泄漏possibly lost可能泄漏需确认still reachable内存未释放但可访问如全局对象可忽略几个例子快速熟悉使用1.new/new[] 与 delete/delete[]new没有delete#include iostream #include string using namespace std; void test_basic_leak() { int* num new int(100); // 分配堆内存 std::string* str new std::string(test leak); // 分配堆内存 { // 业务逻辑后直接返回未释放指针 /* .... */ return ; } delete num; delete str; num nullptr ; str nullptr ; } int main(){ test_basic_leak(); return 0; }g -o test1 -g -O0 test.cc# -g 可获取具体行号new[] 而后 deletevoid test2(){ int *arr new int[10]; /* ... ... */ delete arr; }valgrind --leak-checkfull --show-leak-kindsall --log-filev_2 ./test2容器使用不当void test3(){ vectorint* arr(5) ; for(int i 0 ; i arr.size() ; i) { arr[i] new int(i); } arr.clear(); }valgrind --leak-checkfull --show-leak-kindsall --log-filev_3 ./test3类设计缺陷成员指针未释放浅拷贝导致两次释放class MyClass{ public: MyClass(){ buffer new char[1024]; } ~MyClass(){ delete[] buffer; } private: char *buffer ; }; void test5(){ MyClass obj1; MyClass obj2 obj1 ; }