Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you still trap memory allocation failures in your C++ program [closed]

I am writing some guidelines for the company and I need to answer some tough questions. This one is quite difficult.

The solution can be:

  1. Not track at all. Make sure that objects are allocated using new which will throws an exception when allocation failed. The application will die, and it is not a big deal. PRO - code usually can be very clean.

  2. Track memory allocation failures and reports it accordingly, just like any errors (such as file access error).

Honestly, I have to write much more code if we go with option 2. For example, many std::tring operations involve memory allocation. Such as

std::string str1, str2; str1 = str2; str += str2;

Our software will always run major platforms, not embedded. Somehow I think that option 1 is the way to go. What's your opinion?

like image 606
Glitch Avatar asked Mar 27 '09 20:03

Glitch


1 Answers

I do trap memory allocations, but only occasionally.

In particular, I will occasionally trap a memory allocation where:

  • I know the amount of memory being allocated is very large
  • There is something I can do about it if the allocation fails (ie: gracefully handle the condition with a notice to the user, etc)

That being said, those two things are pretty rare - usually I just end up letting the program die from the exception.

like image 95
Reed Copsey Avatar answered Oct 04 '22 21:10

Reed Copsey