[Exceptional C++ Style] Item 22: To new, Perchance to throw, Part 2: Pragmatic Issues in Memory Management

Balog Pal pasa at lib.hu
Thu Jan 20 05:20:10 EST 2005


[Well, it's actually Item 23 not 22 ;]

> Let's temper our saintly impulses with a practicality.  Many systems 
> allocate memory on an optimistic basis, and don't commit it until the 
> memory is actually used.  Memory allocation on such systems (eg Linux) 
> always succeeds, although, rather unfortunately, any subsequent memory 
> write may fail.  It's not conformant, but it's life.

Herb indeed writes that -- though it's not entirely correct. Memory 
allocation can fail on those systems too, as the address space is not 
infinite, and the memory manager may run out of virtual space even if no 
memory was actually put into use ever.

> In these modern times, new rarely fails anyway.  Virtual memory systems 
> are much more likely to start swapping themselves into oblivion long 
> before memory is exhausted.  As the system grinds down the sysadmin (or 
> even the humble programmer at his desktop) is likely to intervene and 
> start killing things.

Assuming he's patient enough to type at rate one char/minute. :)
On Windows I noticed if memory is used up most applications begin to crash. 
Those MS wrote, and other big names as well.

> Finally, even if you do detect a new failure, there's probably not much 
> you can do about it anyway.

Yeah.

> Recovering from memory exhausting sensibly is difficult - one of our most 
> basic resources has run out after all - and unwinding the stack is 
> generally the best option.

And hoping nothing else begs for memory en-route causing a second exception.
I saw attempts to have reserve memory up front and release it on recovery --  
we shall be aware it may not work at all, as other processes may grab the 
freed memory immediately before out chance comes.

What helps more likey is setting up complete and work-ready objects that 
will not need any additional memory.

> Obviously there are special cases - safety critical systems, for instance. 
> Systems like these need to do more than just catch bad_allocs, though.

Those systems are not likely to use dynamic memory allocation in the first 
place.





More information about the Effective-cpp mailing list