0

Sort of continuation of my question here: Freeing twodimensional arrays stored in a map Tried to follow the suggestion of wrapping my 2D array into a class with destructor and coincidentally managed to reproducably generate an error similar to my project, in the minimal sample. Not all consoles seem to print it (and show weird behavior), but this one does: https://onlinegdb.com/BkhPN6TbL

#include <iostream>
#include <string>
#include <map>

int w = 20;
int h = 20;

class RawGrid
{
public:
    RawGrid(int w, int h)
    {
        width = w;
        data = new bool*[w];

        for(int x = 0; x < width; x++)
            data[x] = new bool[h];
    }
    ~RawGrid()
    {
        if (data)
        {
        for(int x = 0; x < width; x++)
            delete[] data[x];

        delete[] data;
        }
    }

private:
    int width;
    bool** data = nullptr;
};

int main()
{
    std::cout<<"Test A" << std::endl;
    {
        RawGrid grid_a(w, h);
        std::cout<<"Reserved memory" << std::endl;
    }
    std::cout<<"Deleted memory" << std::endl; // because grid_a is out of scope



    std::cout<<"Test B" << std::endl;

    RawGrid grid_a(w, h);
    RawGrid grid_b(w, h);


    std::map<int, RawGrid> cache_map;

    cache_map.emplace(0, grid_a);
    cache_map.emplace(1, grid_b);


    std::cout<<"Reserved memory" << std::endl;

    cache_map.clear();

    std::cout<<"Deleted memory" << std::endl;

    return 0;
}

The error appears to depend on the delete[] data; line (no error if I remove it) but it appears to only happen if used within a map (as Test A shows). How would I safely deconstruct this class?

AlexGeorg
  • 967
  • 1
  • 7
  • 16
  • 3
    You have a rule of three violation. Since you don't have a copy constructor you get a shallow copy and when `cache_map.clear();` runs it leaves `grid_a` and `grid_b` in a bad state and when they get destroyed your program explodes. Implement a proper copy constructor and that will be fixed. – NathanOliver Jan 28 '20 at 14:40
  • Or make your `RawGrid` class non copyable and pass it around by pointer or reference. – Slava Jan 28 '20 at 14:48

0 Answers0