C ++ error exception bad_alloc

I am trying to catch the bad_alloc exception to prove that 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 an exception, my program stops and tries to search for a solution online (Windows). Why is this happening?

EDIT I am now getting an exception, but I have to prove that the destructor is used before the exception is thrown. How can I do it?

+4
source share
3 answers

The problem arises before you begin to dynamically select objects. If you run the program with the debugger attached, you will see that the program terminates because of. Why?

 Obj* ptr[1000000]; 

You cannot declare such a large object with automatic storage time. When main is entered, it tries to allocate space on the stack for this object and cannot do this, resulting in an excess structured stack exception. 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 with delete . Since you never call delete to destroy the objects you created, they are never destroyed.

If you used, say, std::vector<std::unique_ptr<Obj>> instead (or, for that matter, just std::vector<Obj> ), you will see that the destructor will be called for each completely created object Obj .

+8
source

Keep in mind that you are trying to save a very large array on the stack using the ptr array ... most likely your problem is that you overflowed the stack size allocated for your application, by default operator new may fail with the exception of due to lack of memory.

+4
source

I have enclosed all your code in a file, slightly increased the integer constant, finished the class definition for Obj, and reworked your code with some debugging. On a 64-bit Unix server, it correctly throws an β€œexception” when trying to execute the Obj constructor.

 #include<iostream> using namespace std; struct Obj { Obj() { d = new double[20000000000000000LL]; } ~Obj() { cout << "destroyed \n"; } double* d; }; int main(){ Obj* ptr[1000000]; try{ for(int i=0; i<1000; i++){ ptr[i] = new Obj(); cout<<"bah!"<<endl; } } catch(bad_alloc){ cout<<"EXCEPTION"; } cout<<"Done."<<endl; } [ jhumphreys@suoserv ~]$ g++ so2.cpp [ jhumphreys@suoserv ~]$ ./a.out EXCEPTIONDone. [ jhumphreys@suoserv ~]$ 
+1
source

Source: https://habr.com/ru/post/1391733/


All Articles