In article <d24a5b2a.0407212312.66afaa9c@posting.google.com >,
b_srivastava@hotmail.com (Bikash) wrote:
[color=blue]
>Hello,
>
>I am a specific problem in exception handling. The code snippets is
>attached below.
>
>void f()
>{
> char *ptr = new char(20);
> throw 2;
>}
>
>void main(void)
>{
> try
> {
> f();
> }
> catch(...)
> {
> }
>}
>
>The above function calls shows that a memory has been allocated to
>char * pointer. With the throw statment in the subsequent line states
>that there will be memory leak in this time of situation. I just
>wanted to know is there any method to free the memory allocated in the
>catch(...) block.[/color]
There would be a memory leak in any case because no part of the code
even makes the attempt to delete the memory allocated... Maybe a more
resonable example?
void function_that_may_throw();
int main() {
try {
char* ptr = new char( 20 );
function_that_may_throw();
delete ptr;
}
catch ( ... ) { }
}
In this, the solution is to use an auto_ptr:
int main() {
try {
auto_ptr<char> ptr( new char( 20 ) );
function_that_may_throw();
}
catch ( ... ) { }
}
Other examples may call for other solutions, but in all casses RAII is
the way to go. Do a google search on "RAII".