Check assumptions, fix heap overflow

* Add a few asserts on lengths, make sure lengths aren't negative
* Fix two buffer overflows