I have a simple question hopefully - how does one free memory which was allocated in the try block when the exception occurs? Consider the following code:
try
{
The 'correct' answer is RAII and shared_ptr as mentioned above, but just to be complete: in your example, you could substitute
char *heap = new char [50];
with
char *stack = static_cast( alloca(50) );
alloca
is almost identical to malloc
, except that it alocs memory on the stack instead of the heap, so no matter how you function exits (throwing or now), the memory will be reclaimed, and no deletes or frees are necessary.