Search code examples
c++arraysvectorheap-memoryfree

C++ Delete array inside 2D vector


Unfortunately I have to use arrays in order to use another function I have copied. Changing this function to work with vectors would be way over my head. So I wrote a function declaring me bunch of arrays in heap to be stored inside a vector. I now have trouble freeing up that memory at the end.

void _get_X_Y_arrays(std::vector<std::vector<float> > *voronoi, std::vector<std::vector<int*> > *rtrn)
{
    int numberPolygons = voronoi->size();

    for (int i = 0; i < numberPolygons; i++)
    {
        int *x_heap = new int[((*voronoi)[i].size()) / 2];
        int *y_heap = new int[((*voronoi)[i].size()) / 2];
        std::vector<int> x(((*voronoi)[i].size()) / 2);
        std::vector<int> y(((*voronoi)[i].size()) / 2);
        unsigned j = 0;
        int count = 0;
        for (; j < (*voronoi)[i].size(); j += 2, count++)
        {
            x[count] = (int)(*voronoi)[i][j];
            y[count] = (int)(*voronoi)[i][j + 1];

        }
        std::copy(x.begin(), x.end(), &x_heap[0]);
        std::copy(y.begin(), y.end(), &y_heap[0]);

        (*rtrn)[i].push_back(x_heap);
        (*rtrn)[i].push_back(y_heap);

    }
}

The function works well and everything acts like intended. I wrote another function to free up that memory at the end when it's no longer needed:

void _cleanup(std::vector<std::vector<int*> > *rtrn)
{
    for (unsigned i = 0; i < rtrn->size(); i++)
    {
        for (unsigned j = 0; j < (*rtrn)[i].size(); j++)
        {
            delete[] rtrn[i][j][0];
            delete[] rtrn[i][j][1];
        }
    }
}

Unfortunately this causes the program to crash. I don't really know where the error is. It feels like there might be an vector out of scope ..? Just by looking at it and playing with it I'm not able to solve this. What am I doing wrong?


Solution

  • I think you have 3 dimensions array [nbpolygons][2][nbpoints]

    Your code :

    delete[] rtrn[i][j][0]; // delete  rtrn[i][j] index 0
    delete[] rtrn[i][j][1]; // delete  rtrn[i][j] (the same array) index 1
    // => crash
    
    
    rtrn[i].size() always egal 2 
    

    Do :

    void _cleanup(std::vector<std::vector<int*> >& rtrn)
    {
        for (unsigned i = 0; i < rtrn.size(); i++)
        {
            for (unsigned j = 0; j < rtrn[i].size(); j++)
            {
                delete[] rtrn[i][j];
            }
        }
    

    }

    or

    void _cleanup(std::vector<std::vector<int*> >& rtrn)
    {
        for (unsigned i = 0; i < rtrn.size(); i++)
        {
            delete[] rtrn[i][0];
            delete[] rtrn[i][1];
        }
    }