Check assumptions, fix heap overflow

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

Change-Id: I69cf0f74a26cccb5e2f08a0a62fedd06dd1cf486