Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 662
syntagma Avatar asked Jun 18 '15 14:06

syntagma


People also ask

How do you track memory allocation?

Check Computer Memory Usage EasilyTo open up Resource Monitor, press Windows Key + R and type resmon into the search box. Resource Monitor will tell you exactly how much RAM is being used, what is using it, and allow you to sort the list of apps using it by several different categories.

How the memory is allocated in C?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes.

Does C automatically allocate memory?

3.2. 1 Memory Allocation in C Programs The space is allocated once, when your program is started (part of the exec operation), and is never freed. Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable.

What is run-time memory allocation in C?

Memory can be allocated for data variables after the program begins execution. This mechanism is known as runtime memory allocation or dynamic memory allocation.


1 Answers

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)

like image 138
syntagma Avatar answered Sep 28 '22 05:09

syntagma