[ccan] help with gracefully dealing with alloc failure in a recursive function

Joey Adams joeyadams3.14159 at gmail.com
Mon Oct 10 17:26:51 EST 2011


On Thu, Oct 6, 2011 at 9:12 PM, Michael Cohen <scudette at gmail.com> wrote:
> So a couple of points:
>
> -  If you fail to allocate memory what can you do now? Does it even
> make sense to handle this error? Its unlikely that you can recover the
> system to a sufficiently coherent state to be useful. Usually when I
> run out of memory I prefer to segfault rather than try to recover.
> ...

Running out of memory does not mean the application cannot return to a
sane state.  Maybe the user was trying to load a 500MB file.  In this
case, the error handling code will free a lot of memory.

On Fri, Oct 7, 2011 at 9:33 PM, Rusty Russell <rusty at rustcorp.com.au> wrote:
> It really depends.  There's a school of thought which suggests that you
> shouldn't even try to handle it, just exit or crash.  After all, if you
> are writing a library, that's what your users will do.  ...

If the user is binding your library to another programming language,
or is incorporating it into a larger project, there will likely
already be an error handling mechanism in place.  For example,
PostgreSQL has a macro called ereport that produces an error message,
sends it to the client, and (in the case of an error rather than a
warning or informational message) calls longjmp.  If I wanted to write
a quality binding of a C library for PostgreSQL, I would want to be
able to handle errors produced by the library using ereport.  I'd
rather the server gracefully roll back the transaction than kill the
backend.

I used to prefer letting the MMU handle out-of-memory conditions.
Most of the CCAN modules I've contributed work that way.  "Let it
crash" is definitely a legitimate philosophy (notably espoused by
Erlang).  However, many users will want to handle fatal errors in an
application-specific manner.

Simply returning NULL on error, rather than segfaulting, goes a long way.

- Joey


More information about the ccan mailing list