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

Michael Cohen scudette at gmail.com
Fri Oct 7 12:12:55 EST 2011


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.
Perhaps you should just return to the top level and talloc_free the
whole tree and return an error. I dont see how a partial tree is
useful.

- You can still use exceptions using setjmp/longjmp. I am not sure if
thats thread safe. Its probably ok within a single thread.

- Typically recursive solutions are inefficient. You should also be
worried about infinite recursion and particularly stack overflows
(especially on older kernels). A stack based solution is probably
easier and safer.

Michael.

On 6 October 2011 23:54, Daniel Burke <dan.p.burke at gmail.com> wrote:
> I'm wondering what a commonly acceptable method of handling this failure
> would be, my Google-Fu's not giving me answers I like, so   I'm turning to
> the collective wisdom of this list. I suspect my knowledge of other
> languages is poisoning my thought process.
> So parsing XML in a recursive function, with a structure that contains the
> relevant state of the task. My initial plan is to add a variable to the
> structure named "failed", and if an alloc fails I set it, and then test this
> after every function call that can fail, trying to bail out to the head
> function ASAP, where I call the free function on the partial tree I've
> created so far.
> This puts a lot of ugly checking code in what is presently on the clean side
> of what I typically write. Most other languages I'd raise an exception and
> deal with the failure once.
> I've a few existing Linux Kernel style Goto-Exceptions to keep all the error
> code together, and not spread throughout the meat of the functions, however
> my understanding is that it's a Bad Thing (tm) to goto across functions, as
> depending on compiler/flags there's going to have to be some stack
> twiddling, and while my inner assembly programmer says just store SI in the
> data structure, every other bone in my body is telling me this is a capitol
> offense.
> Should I bite the bullet and turn my pretty 1 page function into a 3 page
> function with lots of checking, or is there a clever/easy way to quickly
> bail?
>
>
> regards,
> dan
> --
> "Within C++, there is a much smaller and cleaner language struggling to get
> out"
> --Bjarne Stroustrup
>
> _______________________________________________
> ccan mailing list
> ccan at lists.ozlabs.org
> https://lists.ozlabs.org/listinfo/ccan
>
>


More information about the ccan mailing list