LWN.net Logo

recovery from NULL==malloc(size)

recovery from NULL==malloc(size)

Posted Mar 14, 2008 21:38 UTC (Fri) by jreiser (subscriber, #11027)
In reply to: CERT C Secure Coding Standard: last call for reviewers by ajross
Parent article: CERT C Secure Coding Standard: last call for reviewers

OOM situations on modern (multiprocess, virtual memory) operating systems are not recoverable errors at the level of a single application.

Sometimes they can be, but it requires planning ahead, perhaps from the very beginning of the application which wishes to recover. One strategy is to malloc a safety buffer (say, 5MB), scribble on it, not use it after that, then free() it upon running out. In some situations this buys enough for orderly shutdown, switching modes, or postponement of the application.

... more elaborate rules, like "Don't use dynamic memory allocation at all."

By itself, such a rule is as simple as possible; but implementing it might be cumbersome and elaborate. Or, it might be a true inspiration: make a pre-pass which computes a close upper bound, perform all the malloc() at one time [and do anything else needed to "fully" consume the memory resources], then run the main application which sub-allocates space from the reservations.


(Log in to post comments)

recovery from NULL==malloc(size)

Posted Mar 15, 2008 0:42 UTC (Sat) by aleXXX (subscriber, #2742) [Link]

> > ... more elaborate rules, like "Don't use dynamic memory allocation
> > at all." 
> By itself, such a rule is as simple as possible; but implementing it 
> might be cumbersome and elaborate.

Yes, it's doable but requires quite some effort, which makes sense e.g. 
for embedded systems, where it helps to have the memory requirements 
checked at link time and where you don't want to waste time in malloc().

But as soon as you use some libraries, you probably use dynamic memory. 
STL uses it a lot, so does Qt. C libraries like libxml (it needs to store 
the results somewhere) and gtk probably too.

Alex

recovery from NULL==malloc(size)

Posted Mar 15, 2008 17:43 UTC (Sat) by elanthis (subscriber, #6227) [Link]

STL does not necessarily use dynamic memory allocation.  It makes use of a pattern called
allocators, which make it very possible to use static memory allocation for all objects,
including the internal objects used by STL containers.  This is used in embedded systems quite
a bit.

There are also variations of the STL and various other libraries that are designed for
embedded systems that avoid dynamic memory allocation.  You should see some of the development
frameworks used for making Gameboy, DS, and PSP games.  Unlike the Java games you see on
phones and such, those games push their respective hardware to the limit and need heavy
control over all memory allocations to get there.

Copyright © 2008, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds