Scott Langham
Scott Langham

Reputation: 60341

What are best practices for dealing with out of memory errors?

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.

Upvotes: 1

Views: 373

Answers (3)

doron
doron

Reputation: 28872

The first thing that you should do is try to free up more memory. If you have to periodically scrub objects, now is the time to do it. If all goes well, you may just be able to keep running.

Failing that, you should try to save whatever needs saving to disk and die, if you need extra memory for this, make sure you grab it upfront on startup. Since continuing to run is impossible, you should just die (abort or rethrow the exception).

Upvotes: 2

Michael Smith
Michael Smith

Reputation: 411

Since it runs as a service, it's best to let it crash but make it do so in a controlled manner first by logging the error state and then aborting or self-terminating. The service control manager can be configured to restart the service when it stops out of its control.

If possible you can go further by forcing a controlled dump of itself, which will make it possible to find the cause of the problem.

Your instincts are correct to let it die, because what else is the process to do? Once it arrives in an out-of-memory state it'll never return to a healthy state. RIP process.

Upvotes: 2

PaulH
PaulH

Reputation: 7843

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

Upvotes: 5

Related Questions