This large conditional block


is conditioned on (i == 0) among others.

That means we can only execute this block on
the first iteration of the for loop, and at
that point, nothing has had the chance to make
res contain anything other than NULL.  Much
code directing what to do when (res != NULL)
is actually useless.  Some asserts would be better,
I think.