There is a memory leak example.
void test2(int n)
{
double * ar = new double[n];
...
if (oh_no)
throw exception();
...
delete [] ar;
return;
}
Unwinding the stack removes the variable ar from the stack. But the premature termination of the function
means the delete [] statement at the end of the function is skipped. The pointer is gone, but the memory block
it pointed to is still intact and inaccessible. In short, there is a memory leak.
The leak can be avoided.
void test3(int n)
{
double * ar = new double[n];
...
try {
if (oh_no)
throw exception();
}
catch(exception & ex)
{
delete [] ar;
throw;
}
...
delete [] ar;
return;
}
void test2(int n)
{
double * ar = new double[n];
...
if (oh_no)
throw exception();
...
delete [] ar;
return;
}
Unwinding the stack removes the variable ar from the stack. But the premature termination of the function
means the delete [] statement at the end of the function is skipped. The pointer is gone, but the memory block
it pointed to is still intact and inaccessible. In short, there is a memory leak.
The leak can be avoided.
void test3(int n)
{
double * ar = new double[n];
...
try {
if (oh_no)
throw exception();
}
catch(exception & ex)
{
delete [] ar;
throw;
}
...
delete [] ar;
return;
}