I’m wondering, what are good practices for dealing with out of memory errors.
void SomeTask()
{
try
{
SomeObj obj = new SomeObj();
}
catch( std::bad_alloc& )
{
// What should be done here?
}
// ... more code ...
}
I feel like silently returning is wrong because the program could be running in an indeterminate state. So, what should happen here, should I leave the program to crash, or is there a better alternative? This program runs as a service, so I can’t just pop up an error message. I guess it might be possible to log something if there’s enough memory left to do that. But, I’m just wondering, what do you think I should do in this kind of situation?
Thanks.
Since it’s a service, I would write an error to the system message log. In Windows, you can use the Windows Event Log API. Unless you’ve specified otherwise in your documentation, this is probably where a sysadmin will expect to see the failure report.
Also, in most C++ compilers, std::bad_alloc() has superseded a null return value for failed heap allocations.
-PaulH