What to do if I get std::bad_alloc?

559 views Asked by At

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.

2

There are 2 answers

2
nneonneo On BEST ANSWER

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:

world = new Organism**[worldSizeX]();

(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.

9
Gabriel On

if you use vector then the destructor will be called automatically so you won't need it and your program won't leak

try{
    vector< vector < Organism > >world;
    world.resize(worldSizeX);

    for (int x = 0; x < worldSizeX; x++){
        world[x] = vector<Organism>(worldSizeY);//this calls the default constructor so you don't need the second for loop
    }
}
catch (std::bad_alloc){
    std::cout << "Not enough memory for World size" << worldSizeX << "x" << worldSizeY << std::endl;
    init((int)worldSizeX/2, (int)worldSizeY/2, ants, beetles);
    return;
}