2015-06-18 29 views
7

考虑一个简单的例子:如何跟踪C++标准库调用的内存分配?

#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 

是否有可能追踪正是那些allocs发生(即,数据结构进行分配什么时候到)?

+0

你试过[massif](http://valgrind.org/docs/manual/ms-manual.html)吗? –

+0

@ m.s。我只是做了,但输出是一样的。 – syntagma

+0

运行'valgrind --tool = massif'后需要运行'ms_print massif.out.12345'(数字不同)。 –

回答

2

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

  1. 运行Valgrind的与地块启用:

    valgrind --tool=massif

  2. 使用ms_print来分析来自地块的输出:

    ms_print massif.out.12345 (number varies)