c++ - 如何让 Valgrind 记录所有分配?

标签 c++ c valgrind

即使没有发现内存错误,我也想让 Valgrind 记录分配。如何才能做到这一点?

最佳答案

您将使用 Massif为此(一个 valgrind 工具)。手册链接很容易理解,但为了将来引用,这里是直接从手册中使用它的方法:

valgrind --tool=massif prog

这将生成一个文件,您可以使用 ms_print 对其进行分析.文件名将为 massif.out.<numbers> .只需使用 ms_print获得不错的输出:

ms_print massif.out.12345

您要查找的内容可以在ms_print 输出的末尾找到.对于这个示例程序(他们在手册中显示的程序):

#include <stdlib.h>

void g(void)
{
    malloc(4000);
}

void f(void)
{
    malloc(2000);
        g();
}

int main(void)
{
    int i;
    int* a[10];

    for (i = 0; i < 10; i++) {
        a[i] = malloc(1000);
    }

    f();

    g();

    for (i = 0; i < 10; i++) {
        free(a[i]);
    }

    return 0;
}

我们可以看到谁分配了什么:

->79.81% (8,000B) 0x400589: g (in /home/filipe/dev/a.out)
| ->39.90% (4,000B) 0x40059E: f (in /home/filipe/dev/a.out)
| | ->39.90% (4,000B) 0x4005D7: main (in /home/filipe/dev/a.out)
| |   
| ->39.90% (4,000B) 0x4005DC: main (in /home/filipe/dev/a.out)
|   
->19.95% (2,000B) 0x400599: f (in /home/filipe/dev/a.out)
| ->19.95% (2,000B) 0x4005D7: main (in /home/filipe/dev/a.out)
|   
->00.00% (0B) in 1+ places, all below ms_print's threshold (01.00%)

关于c++ - 如何让 Valgrind 记录所有分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30512000/

相关文章:

c++ - 如何显示存储的信息?

c - 宏中的多个参数

c++ - 为什么 sprintf 在这种情况下会崩溃?

c++ - 当我们在 for 循环条件中使用 cin 时发生了什么?

c++ - wofstream 只创建一个空文件 C++

c# - 无法让 MFC dll 函数在 .net 中运行

profiling - 为什么 valgrind Massif 不报告任何函数名称或代码引用?

c - 在 C 中将变量与字符串进行比较的正确格式是什么?

fedora中C代码编译问题

unit-testing - Valgrind 自动测试——它们在某处使用过吗?