The old loop seemed confusing to me and it overestimated the size of the memory to allocate by a large factor. The old loop would need to have about half of it rewritten to fix the size overestimation and a little more for fixing the original bug. If you think it's very important to keep as much of the old code as possible, I can rewrite the patch that way, but I don't think that's necessary.
Jacob Lifshay