0

After years of programming, I havent had a situation where reasonable malloc or new would fail (maybe because my mallocs are trully reasonable), though I always check for it.

In my case, apps should gracefully (i hope) close with an appropriate log entry. What would you do in this case? Its interesting to hear your approach - do you wait for resources or close the shop?

Puppy
  • 144,682
  • 38
  • 256
  • 465
Ulterior
  • 2,786
  • 3
  • 30
  • 58
  • 1
    It would completely depend on the application, wouldn't it? And once you've settled on your use case, the appropriate mechanism should be obvious. This seems like a bit of a pointless poll to me... – Lightness Races in Orbit Jul 09 '11 at 22:31
  • Gotta agree- this sounds like a subjective poll, and not even language-specific to C or C++. – Puppy Jul 09 '11 at 22:32
  • I'd like to know the way people think in such situations. Yes, c,c++ is just because i do programming in it – Ulterior Jul 09 '11 at 22:36
  • 1
    Related: [Is “Out Of Memory” A Recoverable Error?](http://stackoverflow.com/questions/333736/is-out-of-memory-a-recoverable-error) –  Jul 09 '11 at 22:37
  • @delnan yeah, thanks, could be flagged as a clone – Ulterior Jul 09 '11 at 22:40

2 Answers2

1

I usually have my program shut-down as gracefully as it can, with simple logging of the error message. In C++ I do this by having a catch for std::bad_alloc in main(). By the time the catch executes, destructors called by stack unwinding should have freed some memory, so the logging itself is less likely to fail. I avoid memory allocation (for example by using char * strings rather than std::string strings) in that logging code, to further reduce the chance of the logging failing.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
0

There's pretty much nothing you can do if dynamic allocation fails- there are pretty much no operations written to handle that situation. If it fails, then just let the app crash.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • with a message in a bottle and captain leaves last thing or just crash? – Ulterior Jul 09 '11 at 22:35
  • @user757808: How can you leave a message in a bottle when you can't allocate a bottle? Your I/O libraries will not, and possibly for a given platform cannot, be designed to operate without dynamic allocation. – Puppy Jul 09 '11 at 23:46
  • @DeadMG - Maybe look at your core dump? – KevinDTimm May 15 '12 at 14:14
  • This is bogus. Even when a small allocation fails, you should try to exit gracefully; chances are that stack unwinding will free sufficient resources for the I/O library to output the error message, as @Raedwald suggests. – Fred Foo May 15 '12 at 14:22