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

Joey Adams joeyadams3.14159 at gmail.com
Wed Oct 12 10:24:27 EST 2011


On Tue, Oct 11, 2011 at 6:23 PM, Sam Watkins <sam at nipl.net> wrote:
> As for freeing the XML data structures, aren't they linked together?
> Why not long-jump out of the parser however you'd like to, then call
> free_whole_xml_tree() or whatever?  Or it could just return 'the tree so far'
> with an error code, and let the user free it or keep it.

This is a good idea.  However, you have to ensure that, for every
function call that does a long jump:

 * All objects are attached to the tree.  Those that aren't can be
attached, or they can be freed manually.

 * The tree is in a valid state, at least as far as your tree freeing
code is concerned.  An example of an invalid node would be a tagged
union where the tag hasn't been initialized yet.

> I like the idea of doing alloc within a context, so you can free a whole lot of
> things all together.  I heard that apache uses this to free everything for a
> request, after it's been handled.

PostgreSQL does this too.  It uses a macro called palloc(), which
allocates memory into the current memory context.  The memory context
is freed when an error is reported.  This seems to correspond well
with the transactional nature of a SQL server.

- Joey


More information about the ccan mailing list