How can I track memory allocation of C++ standard library calls?
Asked Answered
E

2

7

Consider this simple example:

#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;
}

When run under Valgrind, it gives me the following output:

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

Is it possible to track exactly where those allocs occured (i.e. which data structure performed allocation and when exactly)?

Earthshaking answered 18/6, 2015 at 14:38 Comment(7)
did you try massif?Heidt
@Heidt I just did but the output was the same.Earthshaking
you need to run ms_print massif.out.12345 (number varies) after running valgrind --tool=massifHeidt
OK, thanks. The output is hard to read at first but it looks like what I'm looking for.Earthshaking
@REACHUS Try massif-visualizer.Dido
Solution should go as an answer and be accepted by the author.Jenisejenkel
as an alternative to massif you can also try heaptrack.Zoba
E
2

The correct way to track C++ library allocation calls is to use Massif, a heap profiler tool (part of Valgrind):

  1. Run Valgrind with Massif enabled:

    valgrind --tool=massif

  2. Use ms_print to analyze output from Massif:

    ms_print massif.out.12345 (number varies)

Earthshaking answered 27/8, 2017 at 17:41 Comment(0)
A
-1

Try giving valgrind the --keep-stacktraces=alloc option. Note using that option will increase the overhead of using valgrind. Here are the docs http://valgrind.org/docs/manual/mc-manual.html#mc-manual.options so you can fine tune what valgrind captures.

Aerobic answered 19/6, 2015 at 1:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.