【问题标题】:How can I track memory allocation of C++ standard library calls?如何跟踪 C++ 标准库调用的内存分配?
【发布时间】:2015-09-04 06:33:00
【问题描述】:

考虑这个简单的例子:

#include <algorithm>
#include <iostream>
#include <list>
#include <numeric>
#include <random>
#include <vector>
#include <iterator>
int main()
{
    std::list<int> l(10);
    std::iota(l.begin(),l.end(),77);

    std::vector<std::list<int>::iterator> v(l.size());
    std::iota(v.begin(), v.end(), l.begin());

    std::vector<int> dest;
    std::copy_if(l.begin(), l.end(), std::back_inserter(dest), [](int i){return i%2==1;});

    for(auto n : dest)
        std::cout << n << " ";
    return 0;
}

在 Valgrind 下运行时,它会给我以下输出:

==27353==   total heap usage: 15 allocs, 15 frees, 380 bytes allocated

是否可以准确跟踪这些分配发生的位置(即哪个数据结构执行分配以及确切的时间)?

【问题讨论】:

  • 你试过massif吗?
  • @m.s.我刚刚做了,但输出是一样的。
  • 运行valgrind --tool=massif后需要运行ms_print massif.out.12345(数量不同)
  • @REACHUS 试试 massif-visualizer。
  • 作为 massif 的替代品,您也可以尝试heaptrack

标签: c++ memory-management stl dynamic-memory-allocation


【解决方案1】:

跟踪 C++ 库分配调用的正确方法是使用Massif,一个堆分析器工具(Valgrind 的一部分):

  1. 在启用 Massif 的情况下运行 Valgrind:

    valgrind --tool=massif

  2. 使用ms_print 分析 Massif 的输出:

    ms_print massif.out.12345 (number varies)

【讨论】:

    【解决方案2】:

    尝试为 valgrind 提供--keep-stacktraces=alloc 选项。请注意,使用该选项会增加使用 valgrind 的开销。这是http://valgrind.org/docs/manual/mc-manual.html#mc-manual.options 的文档,因此您可以微调 valgrind 捕获的内容。

    【讨论】:

      猜你喜欢
      • 2010-10-28
      • 1970-01-01
      • 2012-06-10
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      相关资源
      最近更新 更多