I cannot reproduce this bug on any of my systems for the life of me. I’ve made a few changes, but without knowing the cause for sure I’m can’t tell if they’ll work.
If you’re willing, here is a version with debug symbols, and you could tell me at least on which line the error occurs (via gdb or some other). That’d be appreciated.