Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ bad_alloc exception

I am trying to catch the bad_alloc exception in order to prove that the destructors are used.

Here is my Object:

#include "Obj.h"
#include<iostream>
using namespace std;

Obj::Obj() {
d = new double[200000000];
}
Obj::~Obj() {
cout << "destroyed \n";
}

And the main method:

#include "Obj.h"
#include <iostream>
using namespace std;
int main(){
Obj* ptr[1000000];
try{
    for(int i=0; i<1000; i++){
        ptr[i] = new Obj();
    }
} catch(bad_alloc){
    cout<<"EXCEPTION";
}
}

Instead of catching the exception, my program stops and tries to look for a solution online(Windows). Why is this happening?

EDIT I am getting now the exception, but I should prove that the destructor is used BEFORE the exception is thrown. How should I do that?

like image 386
Dragos Avatar asked Dec 13 '22 06:12

Dragos


1 Answers

The problem occurs before you even start dynamically allocating objects. If you run the program with the debugger attached, you will see that the program is terminated due to a stack overflow. Why?

Obj* ptr[1000000];

You cannot declare so large an object with automatic storage duration. When main is entered, it attempts to allocate space on the stack for this object and fails to do so, causing a stack overflow structured exception to be thrown. Your application does not handle this exception, so the runtime terminates the program.

Note, however, that the Obj destructor will never be called by your program. When you dynamically allocate an object using new, you are responsible for destroying it using delete. Since you do not ever call delete to destroy the objects you created, they are never destroyed.

If you were to use, say, a std::vector<std::unique_ptr<Obj>> instead (or, for that matter, just a std::vector<Obj>), you would see that the destructor would be called for every fully-created Obj object.

like image 101
James McNellis Avatar answered Dec 14 '22 22:12

James McNellis