Make code more defensive

* initialize out-parameter for cases the callee fails to
* add assert for length being within range
* replace post-assert with pre-assert

Also replace the loop with an equivalent memcpy() call