When to delete pointer in try-catch block
Feb 25, 2020 at 3:25pm UTC
Quick best-practice question (note I am not allowed to use any smart pointers in this code). I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted in either the called function or the function in which the memory was first allocated. Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
int main()
{
object* myPtr = new object(); //dynamic memory on heap
foo(*myPtr); //pass pointer to function foo
return 0;
}
void foo(object &pointer)
{
try {
/* do stuff here
with the pointer */
}
catch (const char &e) {
cout<< "An error occured: " << e << endl;
}
catch (...)
cout<< "Caught unknown exception." << endl;
}
}
Should I delete the pointer after the function returns?
1 2 3 4 5 6 7 8
int main()
{
object* myPtr = new object(); //dynamic memory on heap
foo(*myPtr); //pass pointer to function foo
delete myPtr;
return 0;
}
Or in the try-catch blocks?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void foo(object &pointer)
{
try
{
/* do stuff here
with the pointer */
}
catch (const char &e)
{
cout<< "An error occured: " << e << endl;
delete &pointer;
}
catch (...)
{
cout<< "Caught unknown exception." << endl;
delete &pointer;
}
}
Feb 25, 2020 at 3:36pm UTC
Well, in this case: Why do you even create an object with new?
Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?
foo(...) doesn't even know that it is a pointer, hence it shall not delete it.
The exception is completely internal to foo(...). So there is really no reason to worry outside that function about the exception.
And yes: When you don't delete something that is acquired with new it is a memory leak.
Topic archived. No new replies allowed.