简体   繁体   中英

Apparent memory leak while using 2D vector in C++

I decided to use C++ 2D vectors for an applications. While testing some code I encountered a bad alloc error. I read that this may be caused by memory shortage so I investigated my program's memory use by calling the malloc_stats function at different steps in gdb. While I am not sure I completely understand the output of the function, it seems to indicate memory leaks.

I tried to sum up the problem in the short code below:

#include <vector>
#include <iostream>

using namespace std;

vector<vector<double>> get_predictions(){
    vector<vector<double>> predictions;
    for(int i = 0; i < 10; i++){
        vector<double> new_state;
        new_state.push_back(600);
        new_state.push_back(450);
        new_state.push_back(100);
        new_state.push_back(200);
        predictions.push_back(new_state);
    }
    return predictions;
}

int main()
{
    cout << "start" << endl;

    // time loop
    for(int i = 0; i < 10; i++){
        auto predictions = get_predictions();
        // code that uses the latest predictions
    }

    cout << "end" << endl;
    return 0;
}

Now if I call malloc_stats() at the "start" line, the output is similar to this:

Arena 0:
system bytes     =     135168
in use bytes     =      74352
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      74352
max mmap regions =          0
max mmap bytes   =          0

At the "end" step, the function gives:

Arena 0:
system bytes     =     135168
in use bytes     =      75568
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      75568
max mmap regions =          0
max mmap bytes   =          0

The "In use bytes" field clearly increased.

Does it really mean that more allocated memory is held?

If so, why? Shouldn't the allocated content be freed once the different vectors go out of scope?

Then, how to avoid such memory issues?

Thanks a lot

Due to the suggestions in comments, I abandoned malloc_stats, which does not seem to behave as I expected, and tried out Valgrind on my code.

Valgrind confirms that there is no leak in the toy example above.

Concerning my main application, it is a program running on ARM. For reasons unknown to me, the base Valgrind implementation gotten via apt install valgrind did not output the lines concerned by memory leaks. I had to recompile it from sources available on Valgrind website. The problem must come from architecture-specific particularities?

As a side-note, my application also uses CUDA code, which implies many false positives in Valgrind outputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM