Creates 2d
array of organism class pointers:
try{
world = new Organism**[worldSizeX];
for (int x = 0; x < worldSizeX; x++){
world[x] = new Organism*[worldSizeY];
// INITATES world ARRAY
for (int y = 0; y < worldSizeY; y++){
world[x][y] = new Organism;
}
// !INITATES world ARRAY
}
}
catch (std::bad_alloc){
std::cout << "Not enough memory for World size" << worldSizeX << "x" << worldSizeY << std::endl;
deleteWorld(); // DO I NEED THIS?
init((int)worldSizeX/2, (int)worldSizeY/2, ants, beetles);
return;
}
if I have bad_alloc
I want to call init with smaller int values. Do I have to delete
failed array or can I just run it over? And if yes, then how I can delete it, I cant loop through whole array application just crashes.
The reason your program crashes when you try to
deleteWorld
is because your arrays are not completely initialized. Therefore, you may be encountering uninitialized pointers during this process.To avoid this, zero-initialize your arrays:
(note the trailing
()
, which signifies zero-initialization of the array).Now, when you implement
deleteWorld
, you will have to skip over any entries that are NULL.Finally: Yes, you do have to delete everything when you get
bad_alloc
: some objects may already be allocated, and so if you allocated without first deallocating, then you will have a memory leak.