views:

109

answers:

3

Hello, I have something like this:

void Test(void)
{
    char errorMessage[256];

    spintf(errorMessage,... blablabla);
    throw new CustomException(errorMessage);
}

Will this be a memory leak because errorMessage will be not freed? Or will this cause an exception when accessing the message of the exception inside a try{}catch because the errorMessage has been freed when going out from the function¿?

Thanks in advance.

+7  A: 

The memory of errorMessage will already be freed when accessed by the catch handler. However, you could just copy it into a std::string in CustomException's constructor.

A memory leak, on the other hand, could be caused by the exception itself, since you put it on the heap. This is not necessary.

Timbo
A: 

It will not cause a memory leak, but it could result in undefined behavior depending on what you are doing with that exception. I suppose memory leaks can only happen when you allocate dynamic memory

Clash
+7  A: 

The answer is yes, very probably. You should never throw objects created with new. Instead, throw values:

throw CustomException(errorMessage);

and catch using const references:

try {
  ...
}
catch( const CustomException & e ) {
  ...
}

Throwing values means that the compiler handles the lifetime of the thrown object. Also, in your code you may have another problem if the copy constructor for your exception class is not correct - this has nothing specifically to do with exception handling, however.

anon
Agreed. Throw values, catch references and you'll be fine. Throwing pointers is error prone as you'd need a convention as to who is supposed to free them, and that introduces edge-cases e.g. what happens if someone wants to re-throw a caught exception?
MarkR
I am dead against the catching by const reference thing. You should catch by `reference`, but not necessarily `const` as you may wish to modify the exception (add precisions) and then re-throw.
Matthieu M.
@Matthieu Well, you are probably in a small minority. Most people don't want to modify the exception, so using const makes complete sense.
anon
For those who wanted to modify and re-throw, they could always create a copy of the exception object, modify the copy, and then re-throw that. That's slightly less efficient, but since exceptions aren't supposed to occur very often anyway, efficiency shouldn't matter.
Jeremy Friesner
@Jeremy: catching by reference means that to have a copy you would need a `clone` virtual method.
Matthieu M.
@Neil: I just wanted to underline that the `const` here is not necessarily automatic, I freely admit that most of the times you don't actually modify the exception, unless you are using those boost marvels of course, with their system for embedding information.
Matthieu M.