Search code examples
c++c++11memory-leaksstdvectorstdarray

Memory leaks when using complex data structures (array of array of array of vector)


I have a complex data structure defined as:

array<array<array<vector<arc>, 2>, n_ports + 2>, n_times> destinations;

where array and vector are short for std::array and std::vector, n_ports and n_times are unsigned ints and arc is a struct:

struct node { uint port; bool pickup; uint time; };
struct arc { node destination; float cost; };

Basically, to a triple (i,j,k) where 0 <= i < n_times, 0 <= j < n_ports+2, 0 <= k < 2, I associate a vector of arcs, whose dimension I cannot know a priori.

These vectors are not created sequentially, nor are their elements push_back'ed sequentially.

The problem I have is that I find myself with many more arcs than there should be and I suspect that these are vestiges of arcs created earlier and then moved (or copied?) somewhere else when a vector had to be resized.

Here is the most minimal example of what I'm doing that I managed to create, starting from what I am actually working on, that displays the problem.

Any help is appreciated. Am I using the wrong data structure? Should I clean something up after myself? etc.


Solution

  • The problem is that you got the time and port indices backwards. Your arrays are sized with n_times for the port index and n_ports + 2 for the time index. This is probably leading to an out of bounds array access somewhere.

    Remember, std::array is a lot nicer than raw arrays, but it still won't do bounds checking unless you use at().