4 ms·
If you're happy for your program to crash on memory alloc failure, just don't handle them. It's often perfectly acceptable to do so.
by pmjordan 14y ago
If you're happy for your program to crash on memory alloc failure, just don't handle them. It's often perfectly acceptable to do so.
- alexchamberlain 14y agoErrrr... what did you just say!?!
- rubashov 14y agoIf the system is out of memory, and you're not in some special case huge allocation, odds are very high your program can't proceed in any useful way. You're going to have to terminate anyway. Why pretend it's a recoverable exception? It's usually of the same class as a stack overflow. If you can't tolerate that philosophy, you might as well just give up dynamic allocation altogether and have everything in stack allocated std::array's. But you still might blow the stack.
- pmjordan 14y agoThis obviously depends on your environment. I don't recommend doing this in embedded devices or an OS kernel (this is probably why even C++ OS kernels have exceptions disabled, and no STL implementation). But if you're just an app running in an operating system with virtual memory, the kernel's out-of-memory-killer can take you out anytime anyway, so trying to recover from every single failed memory allocation is often futile. The most likely reason to get a failed memory allocation on such a system is that you're out of address space (in 32-bit environments). If this is an issue for your app, you'll need to take higher level design decisions to cope with this fact anyway. If you actually run out of memory (physical + swap) on such a system, you will usually not find out on allocation. Instead, allocations (mmap()/sbrk()) will succeed, but when you write to a previously untouched memory page, it will page fault, not find a backing store for it, and invoke the out-of-memory-killer. Good luck recovering from that. Just to be clear, this doesn't absolve you from managing and conserving your memory diligently. It's just that if you wait for memory allocations to fail before reining in your program, you've probably made your user's system swap so badly it's barely usable. No cookie for you!