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

Joey Adams joeyadams3.14159 at gmail.com
Mon Oct 10 16:52:05 EST 2011


On Thu, Oct 6, 2011 at 5:54 PM, Daniel Burke <dan.p.burke at gmail.com> wrote:
> So parsing XML in a recursive function, with a structure that contains the
> relevant state of the task. ...

You could wrap malloc with a function that records each pointer
allocated, and free the pointers on failure.  This way, you can use
longjmp without leaking memory.

I attached a simple arithmetic expression parser using this approach.
The jmp_buf and list of pointers (stored as a linked list of arrays
called a 'PtrStack') are included in the parser context.

Note that my example uses longjmp to handle both parsing and
allocation errors.  It's convenient in the small, but I would
recommend using return values for parse errors instead.  Doing so
makes it easier to parse alternatives.

I hope this helps.  I might make a CCAN module out of it some day.

- Joey
-------------- next part --------------
A non-text attachment was scrubbed...
Name: expression-parser.c
Type: text/x-csrc
Size: 9102 bytes
Desc: not available
URL: <http://lists.ozlabs.org/pipermail/ccan/attachments/20111010/d135280b/attachment.c>


More information about the ccan mailing list