Tyler Harwood
Tyler Harwood

Reputation: 5

Deleting a dynamically allocated object inside of an object inside of an array

I have a destructor that looks like this:

Tilemap::~Tilemap(void)
{
    if(width>0 && height > 0)
    {
        for (int x = 0; x < getMapWidth(); x++)
        {
            for (int y = 0; y < getMapHeight(); y++)
            {
                if(getTileAtPoint(x,y)->isInteractable())
                {
                    delete getTileAtPoint(x,y)->getInteractable();
                }
            }
        }

        SAFE_DELETE_ARRAY(tileArray);
    }

    return;
}

SAFE_DELETE_ARRAY() is just a macro that looks like this:

#define SAFE_DELETE_ARRAY(ptr) { if(ptr) { delete [](ptr); (ptr)=NULL; } }

The tileArray is a dynamically allocated array that contains tiles which contains interactable objects. Its declaration looks like this:

tileArray = new Tile[mapWidth*mapHeight];

Whenever I delete the double for-loop section of code and just leave this:

Tilemap::~Tilemap(void)
{
    if(width>0 && height > 0)
    {
        SAFE_DELETE_ARRAY(tileArray);
    }
}

I get memory leaks because there is an interactable object that I declared that is not getting deleted. However, when I leave the double for-loops, the code makes it through the for-loops just fine but then crashes on the SAFE_DELETE_ARRAY with this error message:

Unhandled exception at 0x008927CC in Spaceship.exe: 0xC0000005: Access violation reading location 0xFEEEFEEE.

Does anyone know a way to fix this please?

Upvotes: 0

Views: 482

Answers (1)

confusopoly
confusopoly

Reputation: 1245

A very simple pattern: have the destructor of your tile objects delete their Interactable objects if they have them. That way deleting a tile cleans up automatically and you don't have to worry about this on the outside.

Or use some type of smart pointer instead of a raw pointer for the objects referenced by your Tile class.

Upvotes: 1

Related Questions