Re: exception handling, function call and memory
"George" <George@discussions.microsoft.com> wrote in message
news:58CBDA99-C5A5-4BE2-8662-64D420AF8D6A@microsoft.com
[Code]
void perverted()
{
try{
throw exception();
}
catch (exception& e)
{
perverted();
cout << e.what() << endl;
}
}
[/Code]
My question is when the exception is thrown, and goes to exception
handler in catch block, it will do operations in the following
sequences,
(1) execute the exception handler code (since there will be recursive
function call -- stack will ever increasing);
(2) unwind stack.
Unwind the stack first. Write a class whose destructor prints a
diagnostic message, put a local variable of this class inside try block.
The destructor will be called before catch clause is executed.
Of course, stack unwinding here unwinds the try block scope and all
nested scopes, but not the scope of perverted() function's body. The
function's return address, at least, still sits on the stack. So you
still have a recursive call and you still consume the stack with each
such call.
To verify this, put a local variable of the class you've written earlier
at the top of perverted(), outside try or catch blocks. You will see its
destructor is never called before your program crashes.
Runs out of memory because function call will make stack
ever-increasing, right?
Quite.
If it does (2) before (1), I think stack will always be unwinded
before exception handling is called -- then stack will never grow
False dichotomy. "Stack will never grow" doesn't logically follow from
"stack is unwound". It is unwound, but it's not unwound far enough.
there will be no out-of-memory caused by an ever increasing stack.
Is that correct?
That is wrong.
I am confused about why exception handling mechanism will run out of
memory because in exception handle implementation, we just insert
exception handler registration block of the function onto the
beginning of the new function call stack each time there is a
function call
You need an exception stack frame for every try block, not once per
function call. There may be multiple try blocks in a function, and they
can be nested.
Personally, I don't quite see what this sample is supposed to
demonstrate. As far as I can tell, it doesn't matter which part of it
will run out of stack first: the program will crash without ever
printing e.what().
so the memory should be the memory consumed by
function call stuff, I do not think exception handling mechanism
itself will consume additional memory.
Where do you think exception() object itself lives - parallel dimension?
Plus, as I said, there's a stack frame established for the try block, in
addition to one for the function call.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925