Valgrind快速使用

1.Valgrind 的核心组件(工具集)

  • memcheck 内存泄漏、内存错误检测(越界 / 野指针 / 双重释放)

  • cachegrind 缓存命中率,cpu性能分析

  • callgrind 函数调用关系、执行次数、耗时分析

  • helgrind 线程竞争、死锁检测

  • massif 堆内存使用趋势分析

其中mencheck是最常用的,也是本文讲解的

核心用法:

格式:

shell 复制代码
valgrind [通用参数] --tool=memcheck [memcheck参数] 程序名 [程序参数]

基础命令:

shell 复制代码
valgrind --tool=memcheck \
  --leak-check=full \       # 详细检测所有内存泄漏
  --show-leak-kinds=all \   # 显示所有泄漏类型(确定/间接/可能)
  --track-origins=yes \     # 定位内存越界/野指针的根源(精准但稍慢)
  --verbose \               # 输出额外调试信息
  --log-file=valgrind.log \ # 文本日志输出到文件
  --xml=yes \               # 启用 XML 格式输出
  --xml-file=valgrind.xml \ # XML 若使用xml日志输出到文件(必须补充!)
  ./test                    # 待检测的程序(可加参数,如 ./test 123

参数:

  • -- show-leak-kinds=all 显示 4 种泄漏类型:
    • definitely lost:明确泄漏(必须修复)
    • indirectly lost:间接泄漏(如容器内对象泄漏)
    • possibly lost:可能泄漏(需确认)
    • still reachable:内存未释放但可访问(如全局对象,可忽略)

几个例子快速熟悉使用:

1.new/new\[\] 与 delete/delete\[\]

new没有delete

c++ 复制代码
#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;
}
shell 复制代码
g++ -o test1 -g -O0 test.cc  # -g 可获取具体行号

new\[\] 而后 delete

c++ 复制代码
void test2(){
    int *arr = new int[10];
    /*
        ... ... 
    */
    delete arr;
}
shell 复制代码
 valgrind --leak-check=full --show-leak-kinds=all --log-file=v_2 ./test2

容器使用不当

c++ 复制代码
void test3(){
    vector<int*> arr(5) ;
    for(int i = 0 ; i < arr.size() ; ++i) {
        arr[i] = new int(i);
    } 
    arr.clear();
}
shell 复制代码
 valgrind --leak-check=full --show-leak-kinds=all --log-file=v_3 ./test3

类设计缺陷:

成员指针未释放
浅拷贝导致两次释放
c++ 复制代码
class MyClass{
public:
    MyClass(){
        buffer = new char[1024];
    }
    ~MyClass(){
        delete[] buffer;
    }
private:
    char *buffer ;
};
void test5(){
    MyClass obj1;
    MyClass obj2 = obj1 ;
} 
相关推荐
eggwyw7 小时前
C++ union 的一种妙用法
开发语言·c++
ShineWinsu8 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步9 小时前
string的实现(1)
c++·笔记·visual studio
敲上瘾12 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯13 小时前
cpp算法之哈希
c++·算法·哈希算法
lcj251114 小时前
[C++] C++11
开发语言·c++·笔记
小小bugbug17 小时前
带工作窃取的线程池
c++·线程池
南风84111 天前
C++ 四种强制类型转换详解
c++
微笑星河q1 天前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
HaiXCoder2 天前
C++ 表达式怎么读:从一行代码到类型、值类别和生命周期
c++