C++ – Deleting pointers in destructor

c++macospointersxcode

I have some pointers that I allocate in the constructor of a class and then attempt to delete in its destructor:

TileMap::TileMap(int x, int y) {

    mapSize.x = x;
    mapSize.y = y;

    p_p_map = new Tile*[x];

    for(int i = 0; i < x; i++) {

        p_p_map[i] = new Tile[y];

    }

    randomize();

}

TileMap::~TileMap() {

    for(int i = 0; i < mapSize.x; i++) {

        delete p_p_map[i];

    }

    delete p_p_map;

}

void TileMap::randomize() {

    for(int i = 0; i < mapSize.x; i++) {

        for(int j = 0; j < mapSize.y; j++) {

            p_p_map[i][j] = *new Tile(Tile::TileSize * i, Tile::TileSize * j, TileType::randomType());

        }

    }

}

At the end of the program the destructor is called to free the memory of the pointers I allocated, but when it reaches "delete p_p_map[i];" in the destructor, XCode informs me that the pointer was not allocated. I am new to C++, but I feel that I pretty explicitly allocated memory to the pointers in the randomize() function.

What error am I making?

Best Solution

You have to match delete with new and delete[] with new[]. Mixing one up with the other leads to issues. So if you do:

p_p_map = new Tile*[x];

you have to delete it like:

delete[] p_p_map;

and same with

delete[] p_p_map[i];

If you create something like:

pSomething = new Type;

then you delete it like:

delete pSomething;
Related Question