Buffer overrun defensive coding (rebased onto develop)



This is the same as gh-362 but rebased onto develop.

----

See issue #357.