Buffer overrun defensive coding

See issue #357.