I have a piece of code that is creating a tile based level.
class Level {
//Variables
//===================================================
public:
Tile *** TileGrid; //A 2d array of pointers to tiles
int TilesWide, TilesTall;
//Methods
//===================================================
public:
Level::Level(char * fileName);
Level::~Level();
void Draw();
};
I allocate memory for the TileGrid and all is good. I have a destructor set up for the class too.
Level::~Level() {
for (int i = 0; i < TilesTall; i++) {
for (int j = 0; j < TilesWide; j++)
//delete the looped tile being pointed to
delete TileGrid[i][j];
//delete the row
delete [] TileGrid[i];
}
//delete the array of rows
delete [] TileGrid;
}
For giggles I decided I would delete my instance of Level. After I did so, I found that I could still call its Draw method.
In the debugger the values for TilesWide and TilesTall are a huge negative numbers, so nothing draws in my for loops iterating the grid.
Would trying to access a deleted variable not cause some sort of crash?
What you have done is known as “Undefined behavior”.
And undefined behavior doesn’t mean “will crash”, it means anything can happen. The program could format your hard drive, it could play a Bach sonata, it could draw a picture of daffy duck on the screen, it could give you a negative value, and in every case it would be exactly what you asked for.
Not crashing is included, as is crashing.
Now let us suppose a reasonably sane implementation of C++. The method
Level::Drawdoes not vary with which instance ofLevelyou pass it, so what function you call doesn’t rely on the instance. The instance is passed as a parameter to this function as a pointer that points to some memory in the heap that used to be a copy of the variable. Since then, it has been recycled for some other purpose, or maybe contains book-keeping information about the heap — what is there is undefined. (And, accessing it could segfault if the runtime returned the page to the system)You then proceed to interpret that garbage as some values. Things are perfectly fine, because random garbage looks like a C++
integer (in this case, as a negative integer) pretty much always on most systems.Now, once you start dereferencing pointers (and as such, accessing “random” parts of memory), or writing to the state of
this, crashing is likely to happen (if not then, then later, or elsewhere).