I write the code like the following,
// Note that the output object below functions like the C++'s cout. It's my own // implementation of displaying program information and it's insignificant here. try{ try{ //output<<"exhausting the heap"<<endl; int* p = new int(); while(p!=NULL){ p = new int(); } //output<<" heap exhausted"<<endl; } catch(...){ // never reaches here because I use the --force_new_nothrow // Even if I dont't use --force_new_nothrow, the program never // reaches here too... //output<<"heap exhausted. and received an exception"<<endl; } //output<<"now I throw an int"<<endl; throw int(); } catch(...){ // unfortunately, the program never reach here // I guess it's because the exception object is to be created on the heep // but the heap is already exhausted. // So how should I handle the exception when allocation fails occurs? // output some debug imformation //output<<"unkown exception"<<endl; } // never reaches here too... //output<<"end"<<endl; while(1);
Actually the originan code I wrote is more complated. The Exception obj I throw is a class, so is the allocation object type I use to exhaust the heap. I output the address of these object, under the conditions of exhausted heap and unexhausted respectively. I found there is an exception object created on the heap.
So could anyone tell me how to handle the exception when memory allocation fails occurs ?
Note that the link isn't so much about ability to throw exceptions when the heap is full, but if new is able to detect a corrupt heap and throw an exception to complain. And the answer to that is: all bets are off.
Sorry, I don't know what the ARM compiler does when implementing exceptions. If the heap is used or if it plays with the stack until it finally runs out of the final catch block.
Per Westermark, ----------------- "Sorry, I don't know what the ARM compiler does when implementing exceptions. If the heap is used or if it plays with the stack until it finally runs out of the final catch block"
I've tried using the constructor to trace the construction and to print the location of objects. The ARM compiler does use the heap when an exception is thrown. just like class Test{ Test(){ cout<"Test() at "<<this<<endl; } }; when Test t; throw t; I found that there were a temp object created on the stack, and an object created on the heap.
I read the iso c++ standard. It says, "A throw-expression initializes a temporary object, called the exception objec. ... ... The memory for the exception object is allocated in an unspecified way". So that's not strictly defined.
When the heap has been exhausted, the program may still run normally cause memory is just enough for use, but the allocator will not be able to allocate any memory. Then if other kind of exception occurs, the program will not be able to handle it and would just terminate. Although not too likely, there is chance for it to happen.